I wrote a really simple program, forktest.c.
Next, I performed some experiments using this program. Fork is faster
for statically linked executables. It becomes slower as more libraries
are added to a dynamically linked executable.
These tests were done on an x86 machine running Linux.
Here is a transcript of my experiments, followed by the source for forktest.
-- Chris
--- begin transcript ---
Script started on Fri 20 Feb 2009 01:23:10 PM CST
% dietcc forktest.c # link statically against dietlibc
% ./a.out
30864.1 forks per second
% gcc forktest.c # compile with gcc, dynamic linking
% ./a.out
15723.3 forks per second
% gcc forktest.c -lm # pull in the math library
% ./a.out
14792.9 forks per second
% gcc forktest.c -lm -lcurses
% ./a.out
13888.9 forks per second
% gcc forktest.c -lm -lcurses -lpthread
% ./a.out
11961.7 forks per second
% . gcc forktest.c -lm -lcurses -lpthread -lresolv
% ./a.out
11013.2 forks per second
% gcc forktest.c -lm -lcurses -lpthread -lresolv -lssl
% ./a.out
8250.83 forks per second
% gcc forktest.c -lm -lcurses -lpthread -lresolv -lssl -lreadline
% ./a.out
7961.78 forks per second
% exit
Script done on Fri 20 Feb 2009 01:27:20 PM CST
--- end transcript ---
---begin forktest.c---
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int
main(void)
{
double elapsed_secs;
int forks = 0;
clock_t start = clock(), elapsed;
int i;
for(i = 0; i < 25000; i++) {
int waitstatus;
switch (fork()) {
case -1:
perror("fork");
break;
case 0:
exit(42);
default:
wait(&waitstatus);
++forks;
break;
}
}
elapsed = clock() - start;
elapsed_secs = (double)elapsed / CLOCKS_PER_SEC;
printf("%g forks per second\n", (double)forks / elapsed_secs);
exit(0);
}
---end forktest.c---