/* example of comparing overhead of thread vs. process creation */ #define _XOPEN_SOURCE 500 #define _REENTRANT /* Why is the definition of _REENTRANT necessary here? */ #include #include #include #include #include #include #include void * thread_body (void *arg) { return (void *) NULL; } #define US_PER_SEC 1000000 long ticks_per_sec; long usec_per_tick; long n_iterations; clock_t before; clock_t after; void check_elapsed_time (clock_t *d) { *d = after - before; fprintf (stdout, "number of iterations = %ld\n", n_iterations); fprintf (stdout, "elapsed time = %ld ticks\n", *d); fprintf (stdout, "elapsed time = %ld us\n", *d * usec_per_tick); fprintf (stdout, "avg time per iteration = %ld us\n", (*d * usec_per_tick) / n_iterations); } int main(int argc, char **argv) { int i; pthread_attr_t attrs; pthread_t thread; void * value_ptr; pid_t child; int status; clock_t d1, d2; fprintf (stdout, "------------------------------\n"); fprintf (stdout, "system clock ticks per second = %ld\n", (long) CLOCKS_PER_SEC); usec_per_tick = US_PER_SEC / CLOCKS_PER_SEC; fprintf (stdout, "microseconds per clock tick = %ld\n", usec_per_tick); fprintf (stdout, "----------processes-----------\n"); n_iterations = 1000; before = clock(); for (i = 1; i < n_iterations; i++) { if ((child = fork())) { /* we are the parent */ waitpid (child, &status, 0); } else { /* we are the child */ exit (0); } } after = clock(); check_elapsed_time (&d1); fprintf (stdout, "-----------threads------------\n"); n_iterations = 1000; before = clock(); for (i = 1; i < n_iterations; i++) { pthread_attr_init (&attrs); /* use the default attributes */ pthread_create ( &thread, /* place to store the id of new thread */ &attrs, /* thread creation attributes */ thread_body, /* function for thread to execute */ NULL); /* pass no parameter */ pthread_join(thread, &value_ptr); pthread_attr_destroy (&attrs); } after = clock(); check_elapsed_time (&d2); /* Why do we have the loops above? */ fprintf (stdout, "------------------------------\n"); if (d2 > 0.0) fprintf (stdout, "performance ratio = %d\n", (int) (d1/d2)); exit (0); }