Как включить openmp в visual studio 2019
Syntax
/openmp
/openmp:experimental
/openmp:llvm
Remarks
The C++ compiler currently supports the OpenMP 2.0 standard. However, Visual Studio 2019 also now offers SIMD functionality. To use SIMD, compile by 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.
Currently, the /openmp:llvm option only works on the x64 architecture. The 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 .
Syntax
/openmp
/openmp:experimental
/openmp:llvm
Remarks
The C++ compiler currently supports the OpenMP 2.0 standard. However, Visual Studio 2019 also now offers SIMD functionality. To use SIMD, compile by 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.
Currently, the /openmp:llvm option only works on the x64 architecture. The 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 .
Syntax
/openmp
/openmp:experimental
/openmp:llvm
Remarks
The C++ compiler currently supports the OpenMP 2.0 standard. However, Visual Studio 2019 also now offers SIMD functionality. To use SIMD, compile by 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.
Currently, the /openmp:llvm option only works on the x64 architecture. The 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 .
Синтаксис
/openmp
/openmp:experimental
/openmp:llvm
Remarks
Компилятор C++ в настоящее время поддерживает стандарт OpenMP 2,0. однако Visual Studio 2019 теперь также предлагает функции SIMD. Чтобы использовать SIMD, Скомпилируйте с помощью /openmp:experimental параметра. Этот параметр включает как обычные функции OpenMP, так и функции OpenMP SIMD, недоступные при использовании /openmp параметра.
начиная с Visual Studio 2019 версии 16,9 можно использовать экспериментальный /openmp:llvm вариант вместо /openmp для целевой среды выполнения OpenMP LLVM. В настоящее время поддержка в рабочем коде недоступна, так как требуемые библиотеки DLL либомп не являются распространяемыми. Параметр поддерживает те же директивы OpenMP 2,0, что /openmp и. И поддерживают все директивы SIMD, поддерживаемые /openmp:experimental параметром. Он также поддерживает параллельные индексы целых чисел без знака в соответствии со стандартом OpenMP 3,0. Дополнительные сведения см. в разделе Улучшенная поддержка OpenMP для C++ в Visual Studio.
/openmp:llvm В настоящее время параметр работает только в архитектуре x64. Параметр несовместим с /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/C++>язык .
Измените свойство поддержки OpenMP .
Установка данного параметра компилятора программным способом
Пример
В следующем примере показаны некоторые эффекты запуска пула потоков по сравнению с использованием пула потоков после его запуска. При условии, что 64-разрядная, одноядерная, Двухъядерный процессор, пул потоков занимает около 16 мс для запуска. После этого пул потоков будет немного излишним.
При компиляции с помощью /openmp второй вызов test2 никогда не выполняется дольше, чем при компиляции с помощью /openmp- , так как отсутствует запуск пула потоков. В миллионах итераций /openmp версия выполняется быстрее, чем /openmp- версия второго вызова test2. При 25 итерациях обе /openmp- /openmp версии регистрируются меньше, чем степень гранулярности часов.
Если в приложении имеется только один цикл и оно выполняется менее чем на 15 мс (оно корректируется на приблизительную нагрузку на компьютер), /openmp может быть неприемлемо. Если это более высокое значение, можно использовать /openmp .
Процесс установки опускается, и введение начинается после установки. В качестве примера приведу профессиональную версию Visual Studio 2019.
Сначала создайте новый проект, вот консольное приложение C ++.
После создания вы можете найти Обозреватель решений и увидеть созданный вами проект.
следующийЩелкните правой кнопкой мышиЩелкните созданный проект или проект на верхней панели задач, выберитеАтрибуты。
После открытия страницы свойств щелкнитеC/C++ —> Язык, Измените следующую конфигурацию, как показано на рисунке, а затем нажмите ** «Применить», «ОК» **.
Конфигурация тестовой среды прошла успешно
В результате, если вы выведете «hello, world» с тем же количеством строк, что и количество потоков компьютера, конфигурация должна быть успешной.
Мой вывод:
Проверьте улучшение производительности благодаря многопоточности
Результат:
Хотя при этом не достигается оптимальный эффект ускорения многопоточности, все же очевидно, что по мере увеличения количества процессов время выполнения значительно сокращается.
Как подключить openmp в visual studio 2019
Installation platform
Windows10 64-bit system
Visual Studio 2019 (32-bit)
C/C++ environment: MinGW
Download pthread
Environment configuration
Project→Properties→Configuration Properties→VC++ Directory
Add the include path in the include directory, as shown below
Add the lib path in the library directory, as shown in the figure below
Note: According to the system selection, choose x86 for 32-bit and x64 for 64-bit.
In the connector → input, add pthreadVC2.lib as additional dependencies, as shown in the figure below
"Timespec"; "struct" type redefinition
After the above steps are completed, this error will appear in the compiled code. Just edit the beginning of the pthread.h file and find the 33rd line of the code as shown below
Add the following code in line 35:
Test code
Note: If C2440 "=": Cannot convert from "void *" to "pthread_t *" error occurs, just change the .cpp file to the .c file.
Test Results
Configure OpenMP
Use platform
Windows10 64-bit system
Visual Studio 2019 (32-bit)
C/C++ environment: MinGW
Open OpenMP
Debug→Properties→C/C++→All options→OpenMP support is changed to yes, as shown in the figure below
Using Openmp 4/5 in Visual Studio 2019 using clang-cl
I am trying to run a simple project with OpenMP. Since Visual Studio only supports OpenMP 2 so I try to compile and run the project using LLVM clang-cl that comes with Visual Studio 2019. The compilation part seems to be ok, but in the link phase, the linker cannot resolve the OMP functions.
This is my code, there is only 1 file:
My Visual Studio project properties:
- Windows SDK version : 10.0(latest installed version) (10.0.18362.0)
- Platform toolset : LLVM (clang-cl)
- C/c++ — Command Line — Additional Options : /Zc:twoPhase- -Xclang -fopenmp -v
- Linker — Additional Dependencies : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\Llvm\lib\libomp.lib and C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\Llvm\lib\libiomp5md.lib
- Linker — Additional Library Directories : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\Llvm\lib
- Linker — Command Lines — Additional Options : -fopenmp -verbose
Error log when running the project
I am using Visual Studio Community 2019. So how do I config the project in order to OpenMP work?
I have also tried to compile like in this answer and it works.
It works for clang-cl too
But I don’t know how to make Visual Studio build the project using the above way.
Читайте также: