Turn off OpenMP

梦想与她 提交于 2019-12-05 19:52:01
Steve

Hi the easiest way to do this is

omp_set_num_threads(m_iUseableProcessors);

where m_iUseableProcessors is the number of processors you want to split the calculation over. I don't know how to do it without the OpenMP functions. You could probably #ifdef them out, but that makes you turn off OpenMP at compile time.

You can use the environment variable:

set OMP_NUM_THREADS=1

Actually, it will not turn OpenMP off. It will force OpenMP to create only one thread for an application. It works without recompilation. I use this variable to test scalability on 1, 2, 3, 4 etc threads.

You can put the include as follows:

#ifdef _OPENMP_
#include<omp.h> 
#endif

Now if you run your program without -fopenmp flag, it would ignore openmp directives

Jeff

In addition to the suggestion of _OPENMP, you might find it useful to use C99's _Pragma (or __pragma, if you use some C++ compilers - see this StackOverflow question for details) to prevent your code from being littered with #ifdef _OPENMP and #endif, thereby reducing the lines associated with conditional compilation by 3x, and otherwise giving you O(1) control over O(n) instances of OpenMP annotations.

For example, I use the following style in my C99 OpenMP codes. The changes to support C++ should be fairly modest, although possibly compiler-specific (in which case, macros like __GNUC__, __clang__, __INTEL_COMPILER, etc. may be useful).

#ifndef PRAGMA_OPENMP_H
#define PRAGMA_OPENMP_H

#if defined(_OPENMP) && ( __STDC_VERSION__ >= 199901L )

#define PRAGMA(x) _Pragma(#x)

#define OMP_PARALLEL PRAGMA(omp parallel)
#define OMP_PARALLEL_FOR PRAGMA(omp parallel for schedule(static))
#define OMP_FOR PRAGMA(omp for schedule(static))

#define OMP_PARALLEL_FOR_COLLAPSE(n) PRAGMA(omp parallel for collapse(n) schedule(static))
#define OMP_PARALLEL_FOR_COLLAPSE2 OMP_PARALLEL_FOR_COLLAPSE(2)
#define OMP_PARALLEL_FOR_COLLAPSE3 OMP_PARALLEL_FOR_COLLAPSE(3)
#define OMP_PARALLEL_FOR_COLLAPSE4 OMP_PARALLEL_FOR_COLLAPSE(4)

#define OMP_PARALLEL_FOR_REDUCE_ADD(r) PRAGMA(omp parallel for reduction (+ : r) schedule(static))

#else

#warning No OpenMP, either because compiler does not understand OpenMP or C99 _Pragma.

#define OMP_PARALLEL
#define OMP_PARALLEL_FOR
#define OMP_FOR
#define OMP_PARALLEL_FOR_COLLAPSE(n)
#define OMP_PARALLEL_FOR_COLLAPSE2
#define OMP_PARALLEL_FOR_COLLAPSE3
#define OMP_PARALLEL_FOR_COLLAPSE4
#define OMP_PARALLEL_FOR_REDUCE_ADD(r)

#endif

#endif // PRAGMA_OPENMP_H
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!