OpenMP
参考:https://www.cnblogs.com/ospider/p/5265975.html
omp.cpp
1 #include <iostream> 2 #include <omp.h> 3 #include <array> 4 using namespace std; 5 int main(int argc, char **argv) 6 { 7 array<double, 8> arr = {1.2, 2.4, 3.6, 4.8, 6.0, 7.2, 8.4, 9.6}; 8 clock_t time_stt = clock(); 9 10 #pragma omp parallel for 11 for (int i = 0; i < arr.size(); i++ ) 12 { 13 std::cout << arr[i] << std::endl; 14 } 15 16 cout <<"time use is " << 1000* (clock() - time_stt)/(double)CLOCKS_PER_SEC << "ms " << endl; 17 18 clock_t time_st = clock(); 19 for (int i = 0; i < arr.size(); i++ ) 20 { 21 std::cout << arr[i] << std::endl; 22 } 23 24 cout <<"time use is " << 1000* (clock() - time_st)/(double)CLOCKS_PER_SEC << "ms " << endl; 25 clock_t time_s = clock(); 26 #pragma omp parallel for 27 for (char i = 'a'; i <= 'z'; i++) 28 { 29 std::cout << i << std::endl; 30 } 31 cout <<"time use is " << 1000* (clock() - time_s)/(double)CLOCKS_PER_SEC << "ms " << endl; 32 33 clock_t time_sts = clock(); 34 for (char i = 'a'; i <= 'z'; i++) 35 { 36 std::cout << i << std::endl; 37 } 38 cout <<"time use is " << 1000* (clock() - time_sts)/(double)CLOCKS_PER_SEC << "ms " << endl; 39 return 0; 40 41 }
CMakeLists.txt
cmake_minimum_required(VERSION 2.8) project(omp) set(CMAKE_BUILD_TYPE "Release") set(CMAKE_CXX_FLAGS "-std=c++11") #-DEIGEN_USE_MKL_ALL") set(CMAKE_CXX_FLAGS_RELEASE "-O3 -Wall -g") #find_package(OpenCV REQUIRED) FIND_PACKAGE( OpenMP REQUIRED) if(OPENMP_FOUND) message("OPENMP FOUND") set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} ${OpenMP_EXE_LINKER_FLAGS}") endif() #include_directories( ${OpenCV_INCLUDE_DIRS} ${catkin_INCLUDE_DIRS}) add_executable(omp omp.cpp) target_link_libraries(omp ${OpenMP_LIBS})
执行结果:
nzp@nzp-T470:~/桌面/并行/omp_test/build$ ./omp 8.4 3.69.6 1.2 62.4 7.2 4.8 time use is 4.484ms 1.2 2.4 3.6 4.8 6 7.2 8.4 9.6 time use is 0.014ms uo ph aq b c d vi r s t e w x y z f g j k l m n time use is 2.309ms a b c d e f g h i j k l m n o p q r s t u v w x y z time use is 0.062ms
并行并不比串快。