1
0

pa06.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. /**
  2. * PLEASE DO NOT EDIT THIS FILE
  3. */
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <math.h>
  8. #include <errno.h>
  9. #include <sys/time.h>
  10. #include <time.h>
  11. #include "pa06.h"
  12. /**
  13. * The number of seconds difference between t1 and t2
  14. */
  15. double timeDiff(struct timeval t1, struct timeval t2)
  16. {
  17. double time_diff;
  18. double sec_offset = 0;
  19. double t1_sec = t1.tv_sec;
  20. double t2_sec = t2.tv_sec;
  21. double t1_usec = t1.tv_usec;
  22. double t2_usec = t2.tv_usec;
  23. if (t2_usec < t1_usec) {
  24. time_diff = 1e6 + t2_usec - t1_usec;
  25. sec_offset = -1;
  26. } else {
  27. time_diff = t2_usec - t1_usec;
  28. }
  29. time_diff = (t2_sec - t1_sec) + sec_offset + time_diff / 1e6;
  30. return time_diff; // in seconds
  31. }
  32. /**
  33. * Print usage
  34. */
  35. void printUsage()
  36. {
  37. printf("\n"
  38. " Usage: ./pa06 <number-to-test> <number-of-parallel-threads>\n"
  39. "\n");
  40. }
  41. /**
  42. * Program entry point
  43. */
  44. int main(int argc, char * * argv)
  45. {
  46. if(argc != 3) {
  47. printUsage();
  48. return 0;
  49. }
  50. // What was the input number?
  51. uint128 n = alphaTou128(argv[1]);
  52. char * n_str = u128ToString(n);
  53. // How many concurrent threads?
  54. errno = 0; // so we know if strtol fails
  55. int n_threads = strtol(argv[2], NULL, 10);
  56. // Was there an error in the input arguments?
  57. int error = FALSE;
  58. if(errno != 0 || n_threads <= 0) {
  59. fprintf(stderr, "2nd argument must be a valid integer >= 1, aborting.\n");
  60. error = TRUE;
  61. }
  62. if(n_str && strcmp(n_str, argv[1]) != 0) {
  63. fprintf(stderr, "1st argument must be a valid 128-bit integer: '%s' != '%s', aborting.\n", n_str, argv[1]);
  64. error = TRUE;
  65. }
  66. if(error) {
  67. free(n_str);
  68. exit(1);
  69. }
  70. free(n_str);
  71. struct timeval time1;
  72. struct timeval time2;
  73. gettimeofday(&time1, NULL);
  74. printf("Testing if '%s' is prime with %d threads: ", argv[1], n_threads);
  75. fflush(stdout);
  76. int is_prime = primalityTestParallel(n, n_threads);
  77. gettimeofday(&time2, NULL);
  78. if(is_prime) {
  79. printf("TRUE");
  80. } else {
  81. printf("FALSE");
  82. }
  83. printf(", %8.4fs\n", timeDiff(time1, time2));
  84. return EXIT_SUCCESS;
  85. }