初次使用Windows下的OpenMP

本文介绍了在Windows下如何配置OpenMP开发环境,包括在Visual Studio中设置OpenMP支持和设置系统环境变量。同时,给出了两个OpenMP的示例程序,一个是简单的并行打印Hello World,另一个涉及矩阵初始化的并行处理,展示了如何使用`#pragma omp`指令进行并行化操作。
部署运行你感兴趣的模型镜像

一、开发环境配置


1)Windows下面比较容易,安装VS2008 or VS2010之后,新建一个工程并右键点击“属性”,依次进入“配置属性”--》“C/C++”--》“语言”,设置右侧的第五个选项,“OpenMP支持”设定为“是(/openmp)”,这样就完成了开发环境的设定;




2)设置系统环境变量

在环境变量中增加“OMP_NUM_THREADS”变量,数值自己根据你的CPU的性能来设置,一般2、4、8等。




二、OpenMP的helloworld

经过以上环境变量设置之后,可以再VS界面下编写OpenMP程序了,比如建立 一个控制台程序:


#include "stdafx.h"
#include "stdlib.h"
#include <omp.h>



int _tmain(int argc, _TCHAR* argv[])
{
omp_set_num_threads(4);
#pragma omp parallel
printf("hello world!No.%d\n",omp_get_thread_num());
return 0;


}

输出结果如下:




另一个稍微复杂一点的:

// firstMP.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include "stdlib.h"
#include <omp.h>
#define TRUE  1
#define FALSE 0


int _tmain(int argc, _TCHAR* argv[])
{

 int n = 4;
  int *a, **b;


#ifdef _OPENMP
   (void) omp_set_dynamic(FALSE);
   if (omp_get_dynamic()) {printf("Warning: dynamic adjustment of threads has been set\n");}
   (void) omp_set_num_threads(4);
#endif


  if ( (a=(int *)malloc(n*sizeof(int))) == NULL ) {
      perror("array a"); exit(-1);
  }


  if ( (b=(int **)malloc(n*sizeof(int *))) == NULL ) {
      perror("array b"); exit(-1);
  } 
  else {
      for (int i=0; i<n; i++)
          if ( (b[i]=(int *)malloc(n*sizeof(int))) == NULL )
             {perror("array b"); exit(-1);}
  }
 
  #pragma omp parallel shared(n,a,b)
  {
    #pragma omp for
    for (int i=0; i<n; i++)
    {
        a[i] = i + 1;
        #pragma omp parallel for 
        for (int j=0; j<n; j++)
            b[i][j] = a[i];
    }
  } 


  for (int i=0; i<n; i++)
  {
      for (int j=0; j<n; j++)
         printf("b[%d][%d] = %d ",i,j,b[i][j]);
      printf("\n");
  }


  free(a);
  free(b);
  return 0;
}


输出结果为:





您可能感兴趣的与本文相关的镜像

ComfyUI

ComfyUI

AI应用
ComfyUI

ComfyUI是一款易于上手的工作流设计工具,具有以下特点:基于工作流节点设计,可视化工作流搭建,快速切换工作流,对显存占用小,速度快,支持多种插件,如ADetailer、Controlnet和AnimateDIFF等

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值