OpenMP程序 for 循环并行的效率

#pragma omp parallel for 这条语句是用来指定后面的for循环语句变成并行执行的,for循环里的语句变成并行执行后效率会不会提高呢?还是测试一 下吧,测试的时候,循环最好大一些,增加计算量,不然程序耗时太短,很难区分。

#include <omp.h> #include <stdio.h> #include <sys/time.h> void test() { int a = 0; for(int i = 0; i < 10000000; i++) { a = i + 1; } } int main() { int nthrds = 4; omp_set_num_threads(nthrds); timeval tStart,cTime; long long tPassed = 0; gettimeofday(&tStart, 0); for (int i = 0; i < 100; i++) { test(); } gettimeofday(&cTime, 0); cTime.tv_sec -= tStart.tv_sec; cTime.tv_usec -= tStart.tv_usec; tPassed = 1000000LL * cTime.tv_sec + cTime.tv_usec; tPassed /= 1000; printf("Time = %lld/n", tPassed); gettimeofday(&tStart, 0); #pragma omp parallel for for (int i = 0; i < 100; i++) { test(); } gettimeofday(&cTime, 0); cTime.tv_sec -= tStart.tv_sec; cTime.tv_usec -= tStart.tv_usec; tPassed = 1000000LL * cTime.tv_sec + cTime.tv_usec; tPassed /= 1000; printf("Time = %lld/n", tPassed); return 1; }

 result:

[root@c0108 zlt]# g++ omp.c -o omp -fopenmp [root@c0108 zlt]# ./omp Time = 2859 Time = 718 [root@c0108 zlt]#  

在四核的机器上,开了四个线程,加速比基本上是4,果然不错。

 

 

此外,BS一下clock()函数,我向来觉得它一无是处。。。

#include <omp.h> #include <stdio.h> #include <time.h> void test() { int a = 0; for(int i = 0; i < 10000000; i++) { a = i + 1; } } int main() { int nthrds = 4; omp_set_num_threads(nthrds); long start = clock(); for (int i = 0; i < 100; i++) { test(); } long end = clock(); printf("Time = %ld/n", end - start); start = clock(); #pragma omp parallel for for (int i = 0; i < 100; i++) { test(); } end = clock(); printf("Time = %ld/n", end - start); return 1; }  

 

结果:

[root@c0108 zlt]# g++ omp.c -o omp -fopenmp [root@c0108 zlt]# ./omp Time = 2860000 Time = 2860000 [root@c0108 zlt]#  

clock有三个问题:
1)如果超过一个小时,将要导致溢出.
2)函数clock没有考虑CPU被子进程使用的情况.
3)也不能区分用户空间和内核空间.

你可能感兴趣的:(c,测试,parallel)