首页 > 其他 > 详细

OpenMP初探

时间:2018-06-15 18:59:57      阅读:204      评论:0      收藏:0      [点我收藏+]

 

 

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时的这个线程为主线程。

 

OpenMP初探

原文:https://www.cnblogs.com/zhuzhenwei918/p/9188569.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!