/* * ISA 563, Spring 2011 * Copyleft by Muhammad Abdulla */ #include #include #include /* * fork-vs-thread.c -- demonstrate speed differences in process and thread creation */ #define MAX 20000 void fork_task() { exit(0); } void *thread_task(void *data) { pthread_exit(NULL); } void forks() { int i; int s; pid_t pid; for ( i = 0; i < MAX; i++ ) { if ( (pid = fork()) < 0 ) { fprintf(stderr, "fork error.\n"); exit(-1); } else if ( pid == 0 ) { // inside child fork_task(); } else { waitpid(pid, &s, 0); } } } void threads() { int i, j, retval; pthread_t tid; pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); for ( i = 0; i < MAX; i++ ) { // create threads retval = pthread_create(&tid, &attr, thread_task, NULL); if (retval) { printf("Error from pthread_create(). Return value is %d\n", retval); exit(-1); } // wait for thread to finish retval = pthread_join(tid, NULL); if (retval) { printf("Error from pthread_join(). Return value is %d\n", retval); exit(-1); } } } // return time passed in milli-seconds double tp (struct timeval start, struct timeval end) { double t; t = 1000 * (end.tv_sec - start.tv_sec) + (end.tv_usec - start.tv_usec) / 1000.0; return t; } int main ( int argc, char *argv[] ) { struct timeval tv1; struct timeval tv2; // measure forking times gettimeofday(&tv1, NULL); forks(); gettimeofday(&tv2, NULL); printf ( "time to fork %d times: %g (ms)\n", MAX, tp(tv1, tv2) ); // measure thread creation times gettimeofday(&tv1, NULL); threads(); gettimeofday(&tv2, NULL); printf ( "time to create threads %d times: %g (ms)\n", MAX, tp(tv1, tv2) ); }