Advertisement
Guest User

Untitled

a guest
Jan 23rd, 2017
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. #include <iostream>
  2. #include <thread>
  3. #include <vector>
  4. #include <math.h>
  5. #include <memory>
  6. #include <chrono>
  7.  
  8. using namespace std;
  9. using namespace std::chrono;
  10. typedef high_resolution_clock::time_point TimePoint;
  11.  
  12. void PerformSieve(bool* sieve, int start, int inc, int max)
  13. {
  14. for (int i = start; i <= (int)sqrt(max); i+=inc)
  15. {
  16. if (sieve[i])
  17. {
  18. for (int j = i * i; j <= max; j += i)
  19. {
  20. sieve[j] = false;
  21. }
  22. }
  23. }
  24. }
  25.  
  26. // Use the Sieve of Eratosthenes to find all primes up to a certain integer.
  27. // This algorithm is implemented sequentially.
  28. bool* FindPrimeSieveSequential(int n)
  29. {
  30. bool* sieve = (bool*)calloc(n, sizeof(bool));
  31. std::fill_n(sieve, n, true);
  32.  
  33. PerformSieve(sieve, 3, 2, n);
  34.  
  35. // At this point, the indices of all false values in the sieve array
  36. // represent composite numbers.
  37. // The values in all even indices should be ignored; all evens are composite.
  38. // All remaining indices with true values are prime.
  39. return sieve;
  40. }
  41.  
  42. // Use the Sieve of Eratosthenes to find all primes up to a certain integer.
  43. // This algorithm is implemented using parallelism.
  44. bool* FindPrimeSieveInParallel(int n, int numThreads)
  45. {
  46. bool* sieve = (bool*)calloc(n, sizeof(bool));
  47. std::fill_n(sieve, n, true);
  48.  
  49. // Declare array of threads and run sieve on them.
  50. thread threads[numThreads];
  51. for (int i = 0; i < numThreads; i++)
  52. {
  53. threads[i] = thread(PerformSieve, sieve, 3 + i, numThreads, n);
  54. }
  55.  
  56. // Join the threads with the main thread.
  57. for (int i = 0; i < numThreads; i++)
  58. {
  59. threads[i].join();
  60. }
  61.  
  62. // At this point, the indices of all false values in the sieve array
  63. // represent composite numbers.
  64. // The values in all even indices should be ignored; all evens are composite.
  65. // All remaining indices with true values are prime.
  66. return sieve;
  67. }
  68.  
  69. int main(int argc, char *argv[])
  70. {
  71. // unique_ptr<Counter> counter = make
  72. int n = 100000000;
  73.  
  74. TimePoint t1 = high_resolution_clock::now();
  75. // FindPrimeSieveSequential(n);
  76. FindPrimeSieveInParallel(n, 8);
  77. TimePoint t2 = high_resolution_clock::now();
  78.  
  79. auto duration = duration_cast<milliseconds>(t2 - t1).count();
  80. cout << duration << endl;
  81.  
  82. return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement