xref: /haiku/src/tests/system/benchmarks/forkbench.c (revision d3d8b26997fac34a84981e6d2b649521de2cc45a)
1 /*
2  * from ftp://ftp.netbsd.org/pub/NetBSD/misc/gmcgarry/bench/forkbench.tar.gz
3  */
4 
5 /* From 4.4 BSD sys/tests/benchmarks/forks.c. */
6 
7 #include <unistd.h>
8 #include <stdlib.h>
9 #include <stdio.h>
10 #include <sys/time.h>
11 #include <sys/wait.h>
12 
13 /*
14  * Benchmark program to calculate fork+wait
15  * overhead (approximately).  Process
16  * forks and exits while parent waits.
17  * The time to run this program is used
18  * in calculating exec overhead.
19  */
20 
21 int
22 main(argc, argv)
23         char *argv[];
24 {
25         int nforks, i;
26         char *cp;
27         int pid, child, status, brksize;
28         struct timeval before, after;
29 	unsigned elapsed;
30 
31         if (argc < 3) {
32                 printf("usage: %s number-of-forks sbrk-size\n", argv[0]);
33                 exit(1);
34         }
35         nforks = atoi(argv[1]);
36         if (nforks < 0) {
37                 printf("%s: bad number of forks\n", argv[1]);
38                 exit(2);
39         }
40         brksize = atoi(argv[2]);
41         if (brksize < 0) {
42                 printf("%s: bad size to sbrk\n", argv[2]);
43                 exit(3);
44         }
45 
46         gettimeofday(&before, NULL);
47         cp = (char *)sbrk(brksize);
48         if (cp == (void *)-1) {
49                 perror("sbrk");
50                 exit(4);
51         }
52         for (i = 0; i < brksize; i += 1024)
53                 cp[i] = i;
54 	for (i=0; i<nforks; i++) {
55                 child = fork();
56                 if (child == -1) {
57                         perror("fork");
58                         exit(-1);
59                 }
60                 if (child == 0)
61                         _exit(-1);
62                 while ((pid = wait(&status)) != -1 && pid != child)
63                         ;
64         }
65         gettimeofday(&after, NULL);
66 	elapsed = 1000000 * (after.tv_sec - before.tv_sec);
67 	elapsed += (after.tv_usec - before.tv_usec);
68         printf ("Time: %d microseconds.\n", elapsed/nforks);
69         exit(0);
70 }
71