566
社区成员
发帖
与我相关
我的任务
分享
#include<iostream>
#include<omp.h>
#include<ctime>
using namespace std;
void test_omp(int times);
int main()
{
cout << omp_get_num_procs() << endl;
test_omp(1);
test_omp(2);
test_omp(4);
test_omp(9);
test_omp(17);
}
void test_omp(int times)
{
omp_set_num_threads(times);
printf("test get_num_threads result1: %d\n", omp_get_num_threads());
printf("test get_num_procs result1: %d\n", omp_get_num_procs());
clock_t start = clock();
#pragma omp parallel for
for (int i = 0; i < 20; i++)
{
if(i==0)
{
printf("test get_num_threads result2: %d\n", omp_get_num_threads());
printf("test get_num_procs result1: %d\n", omp_get_num_procs());
}
printf( "Hello from thread: No.%d \n", omp_get_thread_num());
for (int j = 0; j < 1000000; j++)
{
double a = 1585876.058578545361;
for (int k = 0;k < 10;k++)
a *= a;
}
}
clock_t end = clock();
printf("%d threads para use time: %fs\n", times, double((end - start)) / CLOCKS_PER_SEC);
}
运行时间问题还是因为每个线程任务量太小不够开并行的,上边代码debug还可以看到一点时间差别,
获取线程数的函数是omp_get_num_threads, 具体参照代码及运行结果可以看出来,才发现过去这么久了已经。。。