#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <pthread.h>

#define NB 10000

void
mysleep()
{
	//endormissement de 1 micro - seconde
	usleep(1);
}

void
mypthread()
{
	pthread_t       th1;
	void           *ret;
	int             i, micro, second;
	struct timeval  chrono1, chrono2;
	struct timezone tempsz;

	gettimeofday(&chrono1, &tempsz);

	for (i = 0; i < NB; i++) {

		if (pthread_create(&th1, NULL, (void *) mysleep, NULL) < 0) {
			fprintf(stderr, "pthread_create error for thread 1\n");
			exit(1);
		}
		(void) pthread_join(th1, &ret);
	}

	gettimeofday(&chrono2, &tempsz);
	micro = chrono2.tv_usec - chrono1.tv_usec;
	if (micro < 0) {
		micro = 1000000 + micro;
		second = chrono2.tv_sec - chrono1.tv_sec - 1;
	} else
		second = chrono2.tv_sec - chrono1.tv_sec;
	printf("Temps Exe avec les Pthreads = %d sec et %d micro sec\n", second, micro);


}

void
myfork()
{
	int             pid, i, micro, second;
	struct timeval  chrono1, chrono2;
	struct timezone tempsz;

	gettimeofday(&chrono1, &tempsz);

	for (i = 0; i < NB; i++) {
		pid = fork();
		if (pid < 0) {	/* error occurred */
			fprintf(stderr, "Fork Failed");
			exit(-1);
		} else if (pid == 0) {	/* child process */
			mysleep();
			exit(0);
		} 
		else {	/* parent process */
			/* parent will wait for the child to complete */
			wait(NULL);
		}	}

	gettimeofday(&chrono2, &tempsz);
	micro = chrono2.tv_usec - chrono1.tv_usec;
	if (micro < 0) {
		micro = 1000000 + micro;
		second = chrono2.tv_sec - chrono1.tv_sec - 1;
	} else
		second = chrono2.tv_sec - chrono1.tv_sec;
	printf("Temps Exe avec le fork = %d sec et %d micro sec\n", second, micro);


}

main(int ac, char **av)
{
	mypthread();
	myfork();
}

