pa12.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /* ======== DO NOT MODIFY THIS FILE ======== */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <sys/time.h>
  5. #include <time.h>
  6. #include "bmp.h"
  7. double timeDiff(struct timeval t1, struct timeval t2)
  8. {
  9. double time_diff;
  10. double sec_offset = 0;
  11. double t1_sec = t1.tv_sec;
  12. double t2_sec = t2.tv_sec;
  13. double t1_usec = t1.tv_usec;
  14. double t2_usec = t2.tv_usec;
  15. //printf("%f %f %f %f\n", t1_sec, t2_sec, t1_usec, t2_usec);
  16. if (t2_usec < t1_usec) {
  17. time_diff = 1e6 + t2_usec - t1_usec;
  18. sec_offset = -1;
  19. } else {
  20. time_diff = t2_usec - t1_usec;
  21. }
  22. time_diff = (t2_sec - t1_sec) + sec_offset + time_diff / 1e6;
  23. return time_diff; //in second
  24. //return (t2.tv_sec - t1.tv_sec) + 10e-6 * (t2.tv_usec - t1.tv_usec);
  25. }
  26. int main(int argc, char **argv)
  27. {
  28. // Check arguments
  29. if (argc < 4) {
  30. printf("Usage: pa12 input output <number of threads>\n");
  31. return EXIT_FAILURE;
  32. }
  33. int maxThread = (int) strtol(argv[3], NULL, 10);
  34. int numThread;
  35. // Load the input file
  36. struct timeval loadTime1;
  37. struct timeval loadTime2;
  38. gettimeofday(& loadTime1, NULL);
  39. BMP_Image *image = BMP_load(argv[1]);
  40. gettimeofday(& loadTime2, NULL);
  41. printf("load time: %8.4f\n", timeDiff(loadTime1, loadTime2));
  42. if (image == NULL)
  43. {
  44. printf("Input file invalid!\n");
  45. return EXIT_FAILURE;
  46. }
  47. // Invert the file
  48. for (numThread = 1; numThread <= maxThread; numThread ++)
  49. {
  50. struct timeval invertTime1;
  51. struct timeval invertTime2;
  52. gettimeofday(& invertTime1, NULL);
  53. BMP_invert(image, numThread);
  54. gettimeofday(& invertTime2, NULL);
  55. printf("%d threads, invert time: %8.4f\n",
  56. numThread, timeDiff(invertTime1, invertTime2));
  57. // invert it back for the next iteration
  58. BMP_invert(image, numThread);
  59. }
  60. // Save the file
  61. struct timeval saveTime1;
  62. struct timeval saveTime2;
  63. gettimeofday(& saveTime1, NULL);
  64. int rv = BMP_save(image, argv[2]);
  65. gettimeofday(& saveTime2, NULL);
  66. printf("save time: %8.4f\n", timeDiff(saveTime1, saveTime2));
  67. if (! rv)
  68. {
  69. printf("Output file invalid!\n");
  70. BMP_destroy(image);
  71. return EXIT_FAILURE;
  72. }
  73. // Destroy the BMP image
  74. BMP_destroy(image);
  75. return EXIT_SUCCESS;
  76. }