fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <random>
  4. #include <omp.h>
  5. #include <chrono>
  6. #include <future>
  7.  
  8. std::random_device os_seed;
  9. const int seed = 1;
  10. std::mt19937 generator(seed);
  11. std::uniform_int_distribution<> distribute(0, 1000);
  12.  
  13. double average(const std::vector<double>& v) {
  14. double sum = 0.0;
  15. #pragma omp parallel for reduction(+:sum)
  16. for (int i = 0; i < v.size(); i++)
  17. sum += v[i];
  18. return sum / v.size();
  19. }
  20.  
  21. double maximum(const std::vector<double>& v) {
  22. double max = 0.0;
  23. #pragma omp parallel for reduction(max:max)
  24. for (int i = 0; i < v.size(); i++)
  25. if (v[i] > max) max = v[i];
  26. return max;
  27. }
  28.  
  29. double minimum(const std::vector<double>& v) {
  30. double min = 1.0;
  31. #pragma omp parallel for reduction(min:min)
  32. for (int i = 0; i < v.size(); i++)
  33. if (v[i] < min) min = v[i];
  34. return min;
  35. }
  36.  
  37. int main() {
  38. int size = 100000000;
  39. std::vector<double> v(size);
  40. for (int i = 0; i < v.size(); i++)
  41. v[i] = distribute(generator) / 1000.0;
  42.  
  43. auto start = std::chrono::steady_clock::now();
  44. double min, max, avg;
  45. min = minimum(v);
  46. max = maximum(v);
  47. avg = average(v);
  48. auto end = std::chrono::steady_clock::now();
  49.  
  50. std::chrono::duration<double> elapsed_seconds = end - start;
  51. std::cout << "Elapsed: " << elapsed_seconds.count() << " seconds" << std::endl;
  52. std::cout << "Min: " << min << " Max: " << max << " AVG: " << avg << std::endl;
  53. }
  54.  
Success #stdin #stdout 4.41s 784216KB
stdin
Standard input is empty
stdout
Elapsed: 0.720547 seconds
Min: 0 Max: 1 AVG: 0.499977