Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <sys/time.h>
- #include <stdio.h>
- #include <pthread.h>
- long time_interval(struct timeval tv1, struct timeval tv2) {
- struct timeval dtv;
- dtv.tv_sec = tv2.tv_sec - tv1.tv_sec;
- dtv.tv_usec=tv2.tv_usec-tv1.tv_usec;
- if(dtv.tv_usec<0) {
- dtv.tv_sec--;
- dtv.tv_usec+=1000000;
- }
- return dtv.tv_sec*1000+dtv.tv_usec/1000;
- }
- volatile int array[100];
- void *heavy_loop(void *param) {
- int index = *((int*)param);
- volatile int i;
- for (i = 0; i < 1000000000; i++)
- array[index] = array[index] + 3;
- }
- int main(int argc, char *argv[]) {
- struct timeval tvs1, tvs2, tvs3, tve1, tve2, tve3;
- struct timezone tz;
- int first_elem = 0;
- int bad_elem = 1;
- int good_elem = 16;
- pthread_t thread_1;
- pthread_t thread_2;
- gettimeofday(&tvs1, &tz);
- heavy_loop((void*)&first_elem);
- heavy_loop((void*)&bad_elem);
- gettimeofday(&tve1, &tz);
- gettimeofday(&tvs2, &tz);
- pthread_create(&thread_1, NULL, heavy_loop, (void*)&first_elem);
- pthread_create(&thread_2, NULL, heavy_loop, (void*)&bad_elem);
- pthread_join(thread_1, NULL);
- pthread_join(thread_2, NULL);
- gettimeofday(&tve2, &tz);
- gettimeofday(&tvs3, &tz);
- pthread_create(&thread_1, NULL, heavy_loop, (void*)&first_elem);
- pthread_create(&thread_2, NULL, heavy_loop, (void*)&good_elem);
- pthread_join(thread_1, NULL);
- pthread_join(thread_2, NULL);
- gettimeofday(&tve3, &tz);
- //printf("%d %d %d\n", array[first_elem],array[bad_elem],array[good_elem]);
- printf("Time without using pthread: %ld ms\n", time_interval(tvs1,tve1));
- printf("Time with wrong using pthread: %ld ms\n", time_interval(tvs2,tve2));
- printf("Time with right using pthread: %ld ms\n", time_interval(tvs3,tve3));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement