1、使用OpenMP与未使用OpenMP的比较。
OpenMP是使用多线程的接口。
以c语言程序举例,即ba.c文件如下:
#include <omp.h> #include <stdio.h> #include <stdlib.h> #include <windows.h> void Test(int n) { int j; for (int i = 0; i < 100000000; ++i) { //do nothing, just waste time j++; } printf("%d, ", n); } int main(int argc, char *argv[]) { int i; #pragma omp parallel for for (i = 0; i < 100; ++i) Test(i); system("pause"); return 1; }
在编译时,参数如下:

编译结果如下:

耗时:9s
注意:我的电脑为双核,所以开启了4个线程分别运行。
未优化的如下:
// #include <omp.h> #include <stdio.h> #include <stdlib.h> #include <windows.h> void Test(int n) { int j; for (int i = 0; i < 100000000; ++i) { //do nothing, just waste time j++; } printf("%d, ", n); } int main(int argc, char *argv[]) { int i; // #pragma omp parallel for for (i = 0; i < 100; ++i) Test(i); system("pause"); return 1; }
在编译时,参数如下:

编译结果如下:

耗时: 24s
不难得知,此程序使用的为单核单线程 ,所以运行速度远远低于使用多核多线程的速度。
2、获取当前线程id、获取总的线程数
#include <omp.h> #include <stdio.h> #include <stdlib.h> #include <windows.h> int main(int argc, char *argv[]) { int nthreads,tid; // fork a team of thread #pragma omp parallel private(nthreads,tid) { //obtian and print thread id tid=omp_get_thread_num(); printf("Hello Word from OMP thread %d\n",tid); // only master thread does this; if(tid==0) { nthreads = omp_get_num_threads(); printf("Number of thread: %d\n",nthreads); } } system("pause"); return 1; }
编译条件如下:

运行结果如下:

每次运行,可以发现顺序是不同的。但是Number of thread: 4永远是在线程0之后出现,并且tid==0时的这个线程为主线程。
原文:https://www.cnblogs.com/zhuzhenwei918/p/9188569.html