Advertisement
AlexMatveev

forPo

Dec 24th, 2011
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. #include <sys/time.h>
  2. #include <stdio.h>
  3. #include <pthread.h>
  4.  
  5. long time_interval(struct timeval tv1, struct timeval tv2) {
  6. struct timeval dtv;
  7. dtv.tv_sec = tv2.tv_sec - tv1.tv_sec;
  8. dtv.tv_usec=tv2.tv_usec-tv1.tv_usec;
  9. if(dtv.tv_usec<0) {
  10. dtv.tv_sec--;
  11. dtv.tv_usec+=1000000;
  12. }
  13. return dtv.tv_sec*1000+dtv.tv_usec/1000;
  14. }
  15.  
  16. volatile int array[100];
  17.  
  18. void *heavy_loop(void *param) {
  19. int index = *((int*)param);
  20. volatile int i;
  21. for (i = 0; i < 1000000000; i++)
  22. array[index] = array[index] + 3;
  23. }
  24.  
  25. int main(int argc, char *argv[]) {
  26. struct timeval tvs1, tvs2, tvs3, tve1, tve2, tve3;
  27. struct timezone tz;
  28. int first_elem = 0;
  29. int bad_elem = 1;
  30. int good_elem = 16;
  31. pthread_t thread_1;
  32. pthread_t thread_2;
  33.  
  34. gettimeofday(&tvs1, &tz);
  35. heavy_loop((void*)&first_elem);
  36. heavy_loop((void*)&bad_elem);
  37. gettimeofday(&tve1, &tz);
  38.  
  39. gettimeofday(&tvs2, &tz);
  40. pthread_create(&thread_1, NULL, heavy_loop, (void*)&first_elem);
  41. pthread_create(&thread_2, NULL, heavy_loop, (void*)&bad_elem);
  42. pthread_join(thread_1, NULL);
  43. pthread_join(thread_2, NULL);
  44. gettimeofday(&tve2, &tz);
  45.  
  46. gettimeofday(&tvs3, &tz);
  47. pthread_create(&thread_1, NULL, heavy_loop, (void*)&first_elem);
  48. pthread_create(&thread_2, NULL, heavy_loop, (void*)&good_elem);
  49. pthread_join(thread_1, NULL);
  50. pthread_join(thread_2, NULL);
  51. gettimeofday(&tve3, &tz);
  52.  
  53. //printf("%d %d %d\n", array[first_elem],array[bad_elem],array[good_elem]);
  54. printf("Time without using pthread: %ld ms\n", time_interval(tvs1,tve1));
  55. printf("Time with wrong using pthread: %ld ms\n", time_interval(tvs2,tve2));
  56. printf("Time with right using pthread: %ld ms\n", time_interval(tvs3,tve3));
  57.  
  58. return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement