[关闭]
@BravoWA 2015-12-27T13:09:06.000000Z 字数 935 阅读 1192

OpenMP求解Pi的例子

未分类


  1. #include <iostream>
  2. #include "omp.h"
  3. using namespace std;
  4. /*
  5. Exercise 2, Serial PI program to parallel PI program
  6. */
  7. static long num_steps = 1000000;
  8. double step;
  9. void main()
  10. {
  11. int i;
  12. double x, pi, sum = 0;
  13. double time_start, time_end;
  14. step = 1.0/(double)num_steps;
  15. //Serial version
  16. time_start = omp_get_wtime();
  17. for (i = 0; i < num_steps; i++)
  18. {
  19. x = (i+0.5)*step;
  20. sum = sum + 4.0/(1.0+x*x);
  21. }
  22. pi = step*sum;
  23. time_end = omp_get_wtime();
  24. cout << scientific << "Calculated results = " << pi << endl;
  25. cout << "Calculated times = " << (time_end - time_start)
  26. << endl;
  27. // Parallel version
  28. sum = 0.0;
  29. omp_set_num_threads(4);
  30. time_start = omp_get_wtime();
  31. #pragma omp parallel for reduction(+:sum)
  32. for (i = 0; i < num_steps; i++)
  33. {
  34. x = (i+0.5)*step;
  35. sum = sum + 4.0/(1.0+x*x);
  36. }
  37. pi = step*sum;
  38. time_end = omp_get_wtime();
  39. cout << "Calculated results = " << pi << endl;
  40. cout << "Calculated times = " << (time_end - time_start)
  41. << endl;
  42. cin.get();
  43. return;
  44. }

VS2012结果:
Calculated results = 3.141593e+000
Calculated times = 4.392572e-002
Calculated results = 3.141593e+000
Calculated times = 3.620780e-002

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注