zoukankan      html  css  js  c++  java
  • OpenMP求完数

    源代码:

     1 #include "stdafx.h"  //必须写在首行,因为其前面的include都会被忽略
     2 #include "omp.h"  
     3 #include <Windows.h>  
     4 #include "time.h" 
     5 #include <iostream>
     6 #include <set>
     7 using namespace std;
     8 
      //串行方式 9 set<int> FinishedNumber(int n) 10 { 11 set<int> s; 12 for (int i = 2; i <= n; i++) 13 { 14 int maxv = (int)(sqrt(double(i)) + 1); 15 int sum = 1; 16 for (int j = 2; j<maxv; j++) 17 if (i%j == 0) 18 sum += j + i / j; 19 if (sum == i) 20 s.insert(i); 21 } 22 return s; 23 } 24

      //并行方式 25 set<int> FinishedNumber(int n, int p) 26 { 27 set<int> s; 28 omp_set_num_threads(p); 29 #pragma omp parallel 30 #pragma omp for 31 for (int i = 2; i <= n; i++) 32 { 33 int maxv = (int)(sqrt(double(i)) + 1); 34 int sum = 1; 35 for (int j = 2; j<maxv; j++) 36 if (i%j == 0) 37 sum += j + i / j; 38 if (sum == i) 39 s.insert(i); 40 } 41 return s; 42 } 43 44 void Test(int step, int count) 45 { 46 /*int step=100000; 47 int count=5;*/ 48 for (int i = 1; i <= count; i++) 49 { 50 int n = i*step; 51 clock_t start_Serial = clock(); 52 53 set<int> result = FinishedNumber(n); 54 printf("n=%d以内的所有完数为: ", n); 55 for (set<int>::iterator it = result.begin(); it != result.end(); it++) 56 { 57 /*cout<<*it<<endl;*/ 58 printf("%d ", *it); 59 } 60 61 clock_t end_Serial = clock(); 62 double timeCollapsedSerial = end_Serial - start_Serial; 63 printf("n=%d, 串行方式运行耗时:%f ", n, timeCollapsedSerial); 64 65 int p = 0; 66 double timeCollapsedParallel = 0; 67 for (int power = 0; power<6; power++) 68 { 69 p = pow(2, power); 70 clock_t start_Parallel = clock(); 71 FinishedNumber(n, p); 72 clock_t end_Parallel = clock(); 73 timeCollapsedParallel = end_Parallel - start_Parallel; 74 float accelerationRate = timeCollapsedSerial / timeCollapsedParallel; 75 printf("n=%d, p=%d, 并行方式运行耗时: %f,加速比: %.3f ", n, p, timeCollapsedParallel, accelerationRate); 76 } 77 78 printf(" "); 79 } 80 } 81 int _tmain(int argc, _TCHAR* argv[]) 82 { 83 int step = 1000 * 1000; 84 int count = 5; 85 Test(step, count); 86 system("pause"); 87 }

    运行结果:

  • 相关阅读:
    系统开发——页面跳转函数的书写
    PC 端自动化最佳方案
    access 点滴
    调用outlook发邮件
    mac安装vmware fusion后设置vmnet8上网
    Gin框架国内安装教程
    mac下一些vscode的初始化设置和使用
    Mac: 使用SDK切换gradle版本
    transfer.sh -- 使用 curl 从命令行上传文件并返回下载地址的文件分享服务(可自架服务端)
    使用ffmpeg转码,解决IDM从youtube下下来的视频在机顶盒上放不出声音问题(使用GPU加速)
  • 原文地址:https://www.cnblogs.com/aaronhoo/p/5436682.html
Copyright © 2011-2022 走看看