System calls and their role in Operating Systems - Time & Space Complexity
System calls let programs ask the operating system to do tasks like reading files or creating processes.
We want to understand how the time taken by system calls grows as the number of calls increases.
Analyze the time complexity of the following code snippet.
for (int i = 0; i < n; i++) {
int fd = open("file.txt", O_RDONLY);
read(fd, buffer, size);
close(fd);
}
This code opens, reads, and closes a file n times in a loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs n times, each time making three system calls: open, read, and close.
- How many times: Each system call happens once per loop iteration, so n times total.
As n grows, the total system calls grow directly with n because each iteration does the same fixed work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 30 system calls (10 open, 10 read, 10 close) |
| 100 | 300 system calls (100 open, 100 read, 100 close) |
| 1000 | 3000 system calls (1000 open, 1000 read, 1000 close) |
Pattern observation: The total work grows steadily and directly with n.
Time Complexity: O(n)
This means the time needed grows in a straight line as the number of system calls increases.
[X] Wrong: "System calls are instant, so their time cost doesn't add up."
[OK] Correct: Each system call involves switching from user mode to kernel mode, which takes time, so many calls add up to more time.
Understanding how system calls scale helps you reason about program efficiency and resource use in real systems.
"What if we opened the file once before the loop and only read and closed inside the loop? How would the time complexity change?"