LoginSignup
4
2

More than 5 years have passed since last update.

macOSのC++で秒速並列化!

Posted at

WindowsのVisual Studioだと設定に<OpenMPSupport>true</OpenMPSupport>を加えて、並列化したいところに#pragma omp parallel forを貼るだけでよしなにやってくれる
macOSでもよしなにしてほしい!しかも短時間で!

ということで時間がない人のための並列化を残す

やること

環境はMBP2016 15inch macOS10.13.4

コンパイラはこんなところ

g++
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でインストール

libompインストール
$ brew install CLIUtils/apple/libomp

これでインストールは終わり、インストールに際して適宜必要なものは入れてほしい

次はテストプログラムを書く

test.cpp
#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

4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2