1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
#include <stdio.h>
#include <stdlib.h>
#include <sys/times.h>
#include <sys/wait.h>
#include <unistd.h>

#define N 1000 /* number of child processes */

/* return real time in seconds since some arbitrary point in the past */
double walltime() {
   static int ticks_per_second = 0;
   if (!ticks_per_second) {
      ticks_per_second = sysconf(_SC_CLK_TCK);
   }
   struct tms timebuf;
   /* times returns the number of real time ticks passed since some
      arbitrary point in the past */
   return (double) times(&timebuf) / ticks_per_second;
}

volatile char global[1048576];

int main() {
   int pagesize = getpagesize();
   for (size_t count = 0; count < sizeof(global) / pagesize; ++count) {
      double t0 = walltime();
      for (int i = 1; i <= N; ++i) {
	 pid_t child = fork();
	 if (child == -1) {
	    perror("unable to fork"); exit(1);
	 }
	 if (child == 0) {
	    /* child process */
	    for (size_t index = 0; index < count; ++index) {
	       global[index*pagesize] = i;
	    }
	    _exit(i);
	 }
      }

      /* parent process */
      pid_t child; int stat;
      while ((child = wait(&stat)) >= 0) {
	 /* nothing to be done */
      }
      double t1 = walltime() - t0;
      printf("%d %.4lf\n", (int) count, t1*1000*1000 / N);
   }
}