How to calculate runtime for fork () system call in C?

I am trying to find the execution time of a fork() system call. Each child process needs to exit immediately, and the parent must wait() on each child object before creating the next one. I also want to use a shell built-in command called time to measure the execution time of a program.

I have this code so far, but not sure if I am doing it right.

 #include <sys/types.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> int global = 100; int main(int argc, char** argv) { int local = 5; pid_t pid; pid = fork(); if (pid < 0) { fprintf(stderr, "error -- failed to fork()"); return 1; } if (pid > 0) { int child_ret; waitpid(pid, &child_ret, 0); printf("parent -- global: %i, local: %i\n", global, local); printf("parent -- child exited with code %i\n", child_ret); } else { global++; local++; printf("child -- global: %i, local: %i\n", global, local); exit (0); } } 
+6
source share
1 answer

Read the time (7) first and consider using clock_gettime (2) and getrusage (2) ; you can use clock_gettime around the fork (in the parent process) if you only want to measure the time for fork (2) syscall (very small - maybe a millisecond) and not very significant.

Use errno (e.g. type strerror(errno) or use perror ) in case of failures.

Please note that fork times may vary slightly from the size of your virtual address space and the size of the resident set . You can also use strace time features; in practice, fork is fast enough (often less than one millisecond, and sometimes several tens of microseconds, because it uses lazy copy-on-write methods)

So, fork fast, a child execve can take a few more microseconds, the program’s launch time for the child is also significant ( ld-linux (8) relocation before running the main program exec ..). What exactly do you want to measure?

In the general case, the child process quickly calls execve (2) , which also takes some time (and, of course, the executable program can take an arbitrarily long time to the end and even never ends if it is a server). It is possible that the time between immediately before the fork and the first significant instruction in the main execve -d program in the child process matters ...

In fact, you can run many processes; the rule of thumb is fork no more than a few hundred times per second, and only if the child quickly execve uses some fast program (for example, /bin/ls from several dozen files or date ). However, you do not want to have more than a dozen or two running processes at the same time (on a laptop or desktop) and, possibly, even less than 5 executable processes ...

+2
source

All Articles