/openmp (Enable OpenMP Support)
Causes the compiler to process #pragma omp directives in support of OpenMP.
Syntax
/openmp
/openmp:experimental
/openmp:llvm
Remarks
#pragma omp is used to specify Directives and Clauses. If /openmp isn’t specified in a compilation, the compiler ignores OpenMP clauses and directives. OpenMP Function calls are processed by the compiler even if /openmp isn’t specified.
The C++ compiler currently supports the OpenMP 2.0 standard. Visual Studio 2019 also now offers SIMD functionality. To use SIMD, compile using the /openmp:experimental option. This option enables both the usual OpenMP features, and OpenMP SIMD features not available when using the /openmp switch.
Starting in Visual Studio 2019 version 16.9, you can use the experimental /openmp:llvm option instead of /openmp to target the LLVM OpenMP runtime. Support currently isn’t available for production code, since the required libomp DLLs aren’t redistributable. The option supports the same OpenMP 2.0 directives as /openmp . And, it supports all the SIMD directives supported by the /openmp:experimental option. It also supports unsigned integer indices in parallel for loops according to the OpenMP 3.0 standard. For more information, see Improved OpenMP Support for C++ in Visual Studio.
The /openmp:llvm option supports the x64 architecture. Starting with Visual Studio 2019 version 16.10, it also supports the x86 and ARM64 architectures. This option isn’t compatible with /clr or /ZW .
Applications compiled by using both /openmp and /clr can only be run in a single application domain process. Multiple application domains aren’t supported. That is, when the module constructor ( .cctor ) is run, it detects if the process is compiled using /openmp , and if the app is loaded into a non-default runtime. For more information, see appdomain , /clr (Common Language Runtime Compilation), and Initialization of Mixed Assemblies.
If you attempt to load an app compiled using both /openmp and /clr into a non-default application domain, a TypeInitializationException exception is thrown outside the debugger, and a OpenMPWithMultipleAppdomainsException exception is thrown in the debugger.
These exceptions can also be raised in the following situations:
- If your application is compiled using /clr but not /openmp , and is loaded into a non-default application domain, where the process includes an app compiled using /openmp .
- If you pass your /clr app to a utility, such as regasm.exe, which loads its target assemblies into a non-default application domain.
The common language runtime’s code access security doesn’t work in OpenMP regions. If you apply a CLR code access security attribute outside a parallel region, it won’t be in effect in the parallel region.
Microsoft doesn’t recommend that you write /openmp apps that allow partially trusted callers. Don’t use AllowPartiallyTrustedCallersAttribute, or any CLR code access security attributes.
To set this compiler option in the Visual Studio development environment
- Open the project’s Property Pages dialog box. For details, see Set C++ compiler and build properties in Visual Studio.
- Expand the Configuration Properties >C/C++ >Language property page.
- Modify the OpenMP Support property.
To set this compiler option programmatically
Example
The following sample shows some of the effects of thread pool startup versus using the thread pool after it has started. Assuming an x64, single core, dual processor, the thread pool takes about 16 ms to start up. After that, there’s little extra cost for the thread pool.
When you compile using /openmp , the second call to test2 never runs any longer than if you compile using /openmp- , as there’s no thread pool startup. At a million iterations, the /openmp version is faster than the /openmp- version for the second call to test2. At 25 iterations, both /openmp- and /openmp versions register less than the clock granularity.
If you have only one loop in your application and it runs in less than 15 ms (adjusted for the approximate overhead on your machine), /openmp may not be appropriate. If it’s higher, you may want to consider using /openmp .
// cpp_compiler_options_openmp.cpp #include #include #include #include volatile DWORD dwStart; volatile int global = 0; double test2(int num_steps) < int i; global++; double x, pi, sum = 0.0, step; step = 1.0 / (double) num_steps; #pragma omp parallel for reduction(+:sum) private(x) for (i = 1; i pi = step * sum; return pi; > int main(int argc, char* argv[]) < double d; int n = 1000000; if (argc >1) n = atoi(argv[1]); dwStart = GetTickCount(); d = test2(n); printf_s("For %d steps, pi = %.15f, %d milliseconds\n", n, d, GetTickCount() - dwStart); dwStart = GetTickCount(); d = test2(n); printf_s("For %d steps, pi = %.15f, %d milliseconds\n", n, d, GetTickCount() - dwStart); >
/openmp (Включить поддержку OpenMP)
Приводит компилятору обрабатывать #pragma omp директивы в поддержку OpenMP.
Синтаксис
/openmp
/openmp:experimental
/openmp:llvm
Замечания
#pragma omp используется для указания директив и предложений. Если /openmp в компиляции не указано, компилятор игнорирует предложения и директивы OpenMP. Вызовы функции OpenMP обрабатываются компилятором, даже если /openmp он не указан.
Компилятор C++ в настоящее время поддерживает стандарт OpenMP 2.0. Visual Studio 2019 также предлагает функциональные возможности SIMD. Чтобы использовать SIMD, выполните компиляцию /openmp:experimental с помощью параметра. Этот параметр включает как обычные функции OpenMP, так и функции OpenMP SIMD, недоступные при использовании коммутатора /openmp .
Начиная с Visual Studio 2019 версии 16.9, можно использовать экспериментальный /openmp:llvm параметр вместо /openmp целевой среды выполнения LLVM OpenMP. Поддержка в настоящее время недоступна для рабочего кода, так как необходимые библиотеки DLL libomp не распространяемые. Параметр поддерживает те же директивы OpenMP 2.0, что /openmp и . Кроме того, он поддерживает все директивы SIMD, поддерживаемые параметром /openmp:experimental . Он также поддерживает неподписанные целые индексы параллельно для циклов в соответствии со стандартом OpenMP 3.0. Дополнительные сведения см. в разделе «Улучшенная поддержка OpenMP для C++ в Visual Studio».
Этот /openmp:llvm параметр поддерживает архитектуру x64. Начиная с Visual Studio 2019 версии 16.10, он также поддерживает архитектуры x86 и ARM64. Этот параметр несовместим с /clr или /ZW не совместим.
Приложения, скомпилированные с помощью обоих /openmp /clr и могут выполняться только в одном процессе домена приложения. Несколько доменов приложений не поддерживаются. То есть при запуске конструктора модуля ( .cctor ) он определяет, компилируется ли процесс с помощью /openmp и если приложение загружается в среду выполнения, отличной от по умолчанию. Дополнительные сведения см. в статьях appdomain ( /clr компиляция среды CLR) и инициализация смешанных сборок.
Если вы пытаетесь загрузить приложение, скомпилированное как с помощью /openmp домена приложения, так и /clr в домен приложения, отличного от по умолчанию, TypeInitializationException исключение возникает за пределами отладчика, а OpenMPWithMultipleAppdomainsException исключение создается в отладчике.
Эти исключения также могут быть вызваны в следующих ситуациях:
- Если приложение компилируется, но не используется /clr и загружается в домен приложений, отличный от по умолчанию, где процесс включает в себя приложение, скомпилированное с помощью /openmp . /openmp
- Если приложение передается /clr в служебную программу, например regasm.exe, которая загружает целевые сборки в домен приложения, отличный от по умолчанию.
Безопасность доступа к коду среды CLR не работает в регионах OpenMP. Если применить атрибут безопасности доступа к коду CLR за пределами параллельного региона, он не будет применяться в параллельном регионе.
Корпорация Майкрософт не рекомендует создавать /openmp приложения, которые позволяют частично доверенным абонентам. Не используйте AllowPartiallyTrustedCallersAttributeатрибуты безопасности доступа к коду CLR.
Установка данного параметра компилятора в среде разработки Visual Studio
- Откройте диалоговое окно Страницы свойств проекта. Подробнее см. в статье Настройка компилятора C++ и свойства сборки в Visual Studio.
- Разверните страницу свойств>конфигурации C/C++>Language.
- Измените свойство поддержки OpenMP.
Установка данного параметра компилятора программным способом
- См. раздел OpenMP.
Пример
В следующем примере показаны некоторые эффекты запуска пула потоков и использование пула потоков после его запуска. При условии, что для запуска пула потоков требуется около 16 мс, одно ядро, двойной процессор. После этого для пула потоков немного дополнительных затрат.
При компиляции с помощью /openmp второго вызова теста 2 никогда не выполняется больше времени, чем при компиляции с использованием /openmp- , так как запуск пула потоков отсутствует. На миллион итерации /openmp версия быстрее, чем /openmp- версия второго вызова test2. В 25 итераций /openmp- /openmp обе версии регистрируются меньше, чем степень детализации часов.
Если у вас есть только один цикл в приложении, и он выполняется менее чем в 15 мс (скорректировано на приблизительную нагрузку на компьютере), /openmp может не быть подходящим. Если это выше, вы можете рассмотреть возможность использования /openmp .
// cpp_compiler_options_openmp.cpp #include #include #include #include volatile DWORD dwStart; volatile int global = 0; double test2(int num_steps) < int i; global++; double x, pi, sum = 0.0, step; step = 1.0 / (double) num_steps; #pragma omp parallel for reduction(+:sum) private(x) for (i = 1; i pi = step * sum; return pi; > int main(int argc, char* argv[]) < double d; int n = 1000000; if (argc >1) n = atoi(argv[1]); dwStart = GetTickCount(); d = test2(n); printf_s("For %d steps, pi = %.15f, %d milliseconds\n", n, d, GetTickCount() - dwStart); dwStart = GetTickCount(); d = test2(n); printf_s("For %d steps, pi = %.15f, %d milliseconds\n", n, d, GetTickCount() - dwStart); >
Installing Open MP for Visual Studio 2019
I have downloaded VS2019 and looks like the omp.h library is already installed, but when I run parallel code, it runs just as a normal program would. So I’m wondering if I have to install the openMp somehow, despite the fact the library is already in there. Also, when I enable the support for OpenMp(In the project settings), the whole code gets a compiling error, despite it runs ok when the setting is disabled.
asked Sep 25, 2019 at 23:13
Lucas Silvestre Lucas Silvestre
11 1 1 bronze badge
What’s the error? A missing library? Or something else?
Sep 25, 2019 at 23:21
At first glance there isn’t anything extra to install: omp.h includes vcomp.lib (vcompd for debug) via #pragma comment(lib, «vcomp») , and I have versions of these libs for all platforms in my install. They’re
Sep 25, 2019 at 23:27
The documentation does say that «If /openmp isn’t specified in a compilation, the compiler ignores OpenMP clauses and directives». So without the support enabled in the project settings you won’t see any difference, no.
Sep 25, 2019 at 23:28
Rup, Error MSB6006 «CL.exe» was terminated with code 2. And I don’t even know what that exe is, and why code 2.
Sep 25, 2019 at 23:30
So after installing the VS, all I got do is enable the suport for openMp and include the
OpenMP Updates and Fixes for C++ in Visual Studio 2019 version 16.10
In our previous blog post about improved OpenMP support in Visual Studio, we announced the addition of the -openmp:llvm switch in Visual Studio 2019 version 16.9 to enable compiled programs to target LLVM’s OpenMP runtime library for the x64 architecture. This switch supports all the OpenMP 2.0 directives that -openmp supports, as well as unsigned integer indices in parallel for loops, and a subset of the SIMD directives that are supported under -openmp:experimental. It also enabled a few correctness fixes. Starting in Visual Studio 2019 version 16.10 Preview 2, the -openmp:llvm switch now works for x86 and arm64. We have also fixed a couple of bugs in 16.10 Preview 3.
-openmp:llvm Now Available for x86 and arm64
Starting in Visual Studio 2019 version 16.10 Preview 2, in addition to X64 support, we have added support for targeting LLVM’s OpenMP runtime library with -openmp:llvm for the x86 and ARM64 architectures. Compiling with -openmp:llvm will automatically add a dynamic link to libomp140.i386.dll (or libomp140d.i386.dll under /DEBUG) when targeting x86, or libomp140.aarch64.dll (or libomp140d.aarch64.dll under /DEBUG) when targeting ARM64. You can find these libraries under the Visual Studio installation directory at VC\Redist\MSVC\\debug_nonredist\\Microsoft.VC142.OpenMP.LLVM . As a reminder, the -openmp:llvm switch is experimental, and features from OpenMP 3.0 that were added with the -openmp:llvm switch in Visual Studio version 16.9 are still only supported with the additional -openmp:experimental flag in Visual Studio version 16.10, and thus are provided with certain limitations in 16.10. In particular, #pragma omp task is not yet available on x86 or arm64, and there is only limited functionality on x64 in 16.10. Lastly, future versions of the LLVM OpenMP runtime DLLs may not be backwards compatible and the current version of these DLLs is not redistributable.
Bug Fixes in 16.10 Preview 3
- return statements inside parallel regions now issue a helpful error message since they are non-conforming. The snippet below would previously crash the compiler with an internal compiler error.
#include int main() < std::cout return 0; >
- The if clause now chooses the correct scope for a variable. In the snippet below, the inner if clause was referencing the outer shared variable i which has a value of 1, rather than the inner private variable i which has the value of 0, causing the program to print “nested” four times instead of one. A similar fix was also applied to the num_threads clause.
#include #include int main(void) < int i = 1; int retVal = 0; #pragma omp parallel if(retVal) default(none) private(i) < printf("hello\n"); i = 0; #pragma omp parallel if(i) default(none) num_threads(4) < printf("nested\n"); >> return 0; >
Our OpenMP Plans
As of 16.10, the currently supported standard is still OpenMP 2.0, though we have made some improvements and fixed some long-standing bugs. We have started the long process to support newer versions of the OpenMP standard. Our goal is to support the most recent OpenMP standard, and this will be done step-by-step, with new features leveraging LLVM’s OpenMP runtime. Our next step for OpenMP will be to support the additional features added in the OpenMP 3.1 standard. Then we will add support for the pragmas and clauses added in the OpenMP 4.5 standard that do not involve offloading. Which features are added first after that will depend on your feedback. We would love to hear from you which specific OpenMP features you would like to see first.
Feedback
We encourage you to try out this update in the latest Visual Studio 2019 version 16.10 Preview. If you encounter a correctness issue in code generated with the -openmp:llvm switch or bugs in the libomp140 DLLs shipped with Visual Studio, please let us know. We can be reached via the comments below, via twitter (@visualc), or via Developer Community.