之前很早就听说 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
本文介绍了一次使用OpenMP进行并行编程的小实验,通过一个简单的例子展示了如何利用OpenMP来加速循环计算任务。文章包括了基本的OpenMP指令使用方法,如设置线程数量、指定并行循环等,并提供了具体的C代码实现及编译说明。
904

被折叠的 条评论
为什么被折叠?



