Advertisement
nex036ara

primes_tbb

Mar 25th, 2012
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. //=======================================================================
  2. //
  3. // SAMPLE SOURCE CODE - SUBJECT TO THE TERMS OF END-USER LICENSE AGREEMENT FOR
  4. // INTEL(R) PARALLEL ADVISOR 2011.
  5. //
  6. // Copyright 2009-2010 Intel Corporation
  7. //
  8. // THIS FILE IS PROVIDED "AS IS" WITH NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
  9. // NOT LIMITED TO ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  10. // PURPOSE, NON-INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS.
  11. //
  12. // ========================================================================
  13.  
  14. #include "stdafx.h"
  15. #include <stdio.h>  
  16. #include <tbb/mutex.h>
  17. #include <tbb/blocked_range.h>
  18. #include <tbb/parallel_for.h>
  19. #include <tbb/partitioner.h>
  20.  
  21. typedef tbb::blocked_range<int> int_blocked_range;
  22.  
  23. const int limit         = 3000000;
  24. const int correctCount  = 216816;
  25. int primes = (limit >= 2) ? 1 : 0;  // two is a prime, so count it
  26. tbb::mutex primeMutex;
  27.  
  28. void Tick() {
  29.     tbb::mutex::scoped_lock lockUntilScopeExit(primeMutex);
  30.     primes++;
  31. }
  32.  
  33. bool IsPrime(int p) {
  34.     for (int i = 3; i*i <= p; i += 2) {
  35.         if (p/i*i == p) return false;
  36.     }
  37.     return true;
  38. }
  39. class LoopBody {
  40. public:
  41.     LoopBody() {}
  42.     void operator() (const int_blocked_range& range) const {
  43.         const int upper = 3 + 2*range.end();  // expand range
  44.         for (int p = 3 + 2*range.begin(); p < upper; p+=2) {
  45.             if (IsPrime(p)) Tick();
  46.         }
  47.     }
  48.  };
  49.  
  50. #include <tbb/task_scheduler_init.h>
  51.  
  52. int _tmain(int argc, _TCHAR* argv[])
  53. {
  54.     tbb::task_scheduler_init tsi;  
  55.  
  56.     tbb::parallel_for(
  57.         int_blocked_range(3-3, (limit-3)/2 + 1),   // make contiguous range 0..
  58.         LoopBody(),
  59.         tbb::auto_partitioner());
  60.  
  61.     printf("primes = %d\n", primes);
  62.     return primes != correctCount;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement