WindowsのVisual Studioだと設定に<OpenMPSupport>true</OpenMPSupport>
を加えて、並列化したいところに#pragma omp parallel for
を貼るだけでよしなにやってくれる
macOSでもよしなにしてほしい!しかも短時間で!
ということで時間がない人のための並列化を残す
やること
環境はMBP2016 15inch macOS10.13.4
コンパイラはこんなところ
Configured with: --prefix=/Applications/Xcode.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 9.1.0 (clang-902.0.39.2)
Target: x86_64-apple-darwin17.5.0
Thread model: posix
まずは必要なものをbrew
でインストール
$ brew install CLIUtils/apple/libomp
これでインストールは終わり、インストールに際して適宜必要なものは入れてほしい
次はテストプログラムを書く
#include <omp.h>
#include <stdio.h>
int main() {
#pragma omp parallel
printf("Hello from thread %d, nthreads %d\n", omp_get_thread_num(), omp_get_num_threads());
}
最後にコンパイルして実行
$ g++ -Xpreprocessor -fopenmp -I$(brew --prefix libomp)/include $(brew --prefix libomp)/lib/libomp.dylib test.cpp
$ ./a.out
Hello from thread 0, nthreads 8
Hello from thread 3, nthreads 8
Hello from thread 2, nthreads 8
Hello from thread 4, nthreads 8
Hello from thread 6, nthreads 8
Hello from thread 7, nthreads 8
Hello from thread 1, nthreads 8
Hello from thread 5, nthreads 8
$
はい、ちゃんと動いてそう
ここまで、10分もかからない
あとは、並列化したいforの前に、#pragma omp parallel for
だの#pragma omp parallel for schedule(dynamic, 1) num_threads(NUM_THREAD)
だの書いて(詳しくは調べて)、
このオプション
-Xpreprocessor -fopenmp -I$(brew --prefix libomp)/include $(brew --prefix libomp)/lib/libomp.dylib
を足してコンパイルでおしまい。
参考
https://github.com/CLIUtils/homebrew-apple
https://stackoverflow.com/questions/47081991/is-c-compilable-with-openmp-and-boost-on-macos/47225639#47225639
https://gist.github.com/fyears/59e67cf0f521bc199235
https://qiita.com/kaityo256/items/ae9329dae24ea8828ae0