/* fk3.c: fork() cost against the storage the parent holds. * * p[0] is read after the loop so the allocation cannot be optimised * away. Usage: ./fk3 [megabytes] [forks]; the cost is child and parent * CPU, so it is the fork, not the wait, that is being charged. * * See bench/README.md and notes/investigation.md. */ #include #include #include #include #include #include #ifndef CLK_TCK #define CLK_TCK 100 /* z/OS reports 100; the divisor below assumes it */ #endif int main(int argc, char **argv) { long mb = argc > 1 ? atol(argv[1]) : 0; int n = argc > 2 ? atoi(argv[2]) : 100; char *p = nullptr; if (mb > 0) { p = malloc((size_t)mb * 1024 * 1024); if (!p) { printf("malloc failed\n"); return 1; } memset(p, 'x', (size_t)mb * 1024 * 1024); } struct tms a, b; times(&a); for (int i = 0; i < n; i++) { pid_t c = fork(); if (c == 0) _exit(0); int st; waitpid(c, &st, 0); } times(&b); clock_t t = (b.tms_utime - a.tms_utime) + (b.tms_stime - a.tms_stime) + (b.tms_cutime - a.tms_cutime) + (b.tms_cstime - a.tms_cstime); printf(" %4ld MB: %6.2f s (%5.2f ms per fork)", mb, (double)t / 100.0, (double)t / 100.0 * 1000.0 / n); if (p) printf(" [p[0]=%c]", p[0]); printf("\n"); return 0; }