openMP加速程序运行

之前很早就听说 OPENMP的大名,只是一直没把它用上。 今天小试了一下,效果还不错的样子。

常常加入预编译  

#pragma omp parallel num_threads(5) 即可, num_thread() 来限定线程数
#pragma omp parallel for   用于循环的加速

#include <omp.h>
#include <math.h>
#include <time.h>
#include <stdio.h>

int main(int argc, char *argv[]) {
    int i, nthreads;
    clock_t clock_timer;
    double wall_timer;
    double c[1000000]; 
    for (nthreads = 1; nthreads <=8; ++nthreads) {
        clock_timer = clock();
        wall_timer = omp_get_wtime();
        #pragma omp parallel for private(i) num_threads(nthreads)
        for (i = 0; i < 1000000; i++) 
             c[i] = sqrt(i * 4 + i * 2 + i); 
        printf( "threads: %d  take time is %lf \n", nthreads,   (omp_get_wtime() - wall_timer));
    }
}

然后打开terminal,  $  gcc openmp.c -o openmp -fopenmp -lm    

-fopenmp为openMP的编译库, -lm由于用到了sqrt数学库

在我的i7-4790里,运行结果如下:(在虚拟机里运行,只分配了两个核心给它)

threads: 1  take time is 0.007695 
threads: 2  take time is 0.002776 
threads: 3  take time is 0.003704 
threads: 4  take time is 0.004672 
threads: 5  take time is 0.004259 
threads: 6  take time is 0.002638 
threads: 7  take time is 0.005959 
threads: 8  take time is 0.004136

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值