#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cassert>
#include <stdio.h>
#include <pthread.h>
#include "stopwatch.h"


#define loop_maximum 2000


static void * f(void *) {
  return NULL;
  }


#define timeit(_sw, stmts) \
  do { \
    unsigned _i; \
    _sw.start(); \
    for (_i = 0; _i < loop_maximum; _i++) { stmts ; } \
    _sw.stop(); \
    } while (false)


int main(int argc, char * argv[]) {

  int i;
  stopwatch s, oh;

  timeit(oh,);
  printf("Loop overhead is %d usec for %d iterations, %g usec/iteration.\n",
	 oh.elapsed(), loop_maximum, 
	 ((double) oh.elapsed())/((double) loop_maximum));

  pid_t pid;
  timeit(s, 
    switch (pid = fork()) {
      case 0: 
	exit(EXIT_SUCCESS);
      case -1:
	perror("fork() error:");
	exit(EXIT_FAILURE);
      default:
	assert(wait(NULL) == pid);
      }
    );

  printf("Time per fork() call for %d calls: %g usec.\n", loop_maximum,
	 ((double) s.elapsed())/((double) loop_maximum));


  pthread_t tid;
  int e;
  timeit(s, 
    if ((e = pthread_create(&tid, NULL, f, NULL))) {
      printf("pthread_create() failed with error %d.\n", e);
      return EXIT_FAILURE;
      }
    if ((e = pthread_join(tid, NULL))) {
      printf("pthread_join() failed with error %d.\n", e);
      return EXIT_FAILURE;
      }
    );

  printf("Time per pthread_create() call for %d calls: %g usec.\n", loop_maximum,
	 ((double) s.elapsed())/((double) loop_maximum));


  return EXIT_SUCCESS;
  }


syntax highlighted by Code2HTML, v. 0.9