本文主要是介绍编译生成tbb动态库并用cmake链接,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
本文关于基于github源码编译tbb生成动态库,并在cmake中使用
步骤一: 编译tbb并生成shared library
在github下载项目源码
git clone git@github.com:oneapi-src/oneTBB.gitcd oneTBBmkdir build && cd build
开始编译
参考:
Alex Reinking
cmake -G Ninja -S . -B build-shared -DBUILD_SHARED_LIBS=YES -DCMAKE_BUILD_TYPE=Release -DCMAKE_CXX_FLAGS=-DTBB_ALLOCATOR_TRAITS_BROKENcmake --build build-sharedcmake --install build-shared --prefix _install
执行完成后,在build文件夹里可以看到新生成的文件夹
动态库生成。
步骤二:通过cmakelists建立链接
项目如上图结构组织,具体内容如下
CMakeLists.txt
cmake_minimum_required(VERSION 2.8.9)
project (hello_tbb)set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC -std=c++11 -fpermissive -Wall -Werror -O2 -Wno-deprecated -Wno-deprecated-declarations")add_executable(hello_tbb main.cpp)
#target_include_directories(hello_tbb PUBLIC ${CMAKE_HOME_DIRECTORY}/third_party/opencv-3.4.3/16.04/include)#target_link_directories(hello_tbb PUBLIC ${CMAKE_HOME_DIRECTORY}/third_party/opencv-3.4.3/16.04/lib)
target_include_directories(hello_tbb PUBLIC ${CMAKE_HOME_DIRECTORY}/third_party/tbb_lib/include)
target_link_directories(hello_tbb PUBLIC ${CMAKE_HOME_DIRECTORY}/third_party/tbb_lib/lib)#set(OpenCV_LIBS
# opencv_ml opencv_highgui opencv_imgproc opencv_calib3d
# opencv_features2d opencv_imgcodecs opencv_videoio opencv_video
# opencv_aruco opencv_ccalib opencv_hdf opencv_core)target_link_libraries(hello_tbb tbb)#target_link_libraries(hello_tbb PUBLIC ${OpenCV_LIBS})
main.cpp
#include <iostream>
#include <random>
#include <chrono>
#include <cmath>
#include <tbb/tbb.h>inline double calculate_objective_value(double x)
{return std::sin(x);
}inline double calculate_derivative_value(double x)
{return std::cos(x);
}int main()
{std::random_device seed;std::default_random_engine engine(seed());std::uniform_real_distribution<double> uniform_dist(0.0, 10.0);constexpr int num_elements = 1000000;std::vector<double> x_optimal(num_elements);auto perform_gradient_descent = [&](int i){constexpr double epsilon = 1e-15;constexpr double rate = 0.99;double a = 0.50;double x = uniform_dist(engine);while (true){const double delta = a * calculate_derivative_value(x);x -= delta;a *= rate;if (delta < epsilon) { break; }}x_optimal[i] = x;};const auto t_0 = std::chrono::system_clock::now();tbb::parallel_for(0, num_elements, perform_gradient_descent);const auto t_1 = std::chrono::system_clock::now();for (int i = 0; i < num_elements; ++ i) { perform_gradient_descent(i); }const auto t_2 = std::chrono::system_clock::now();const int elapsed_time_parallel = std::chrono::duration_cast<std::chrono::milliseconds>(t_1 - t_0).count();const int elapsed_time_serial = std::chrono::duration_cast<std::chrono::milliseconds>(t_2 - t_1).count();std::cout << "parallel: " << elapsed_time_parallel << " [ms]" << std::endl;std::cout << "serial: " << elapsed_time_serial << " [ms]" << std::endl;return 0;
使用cmakelists编译成功后,运行OK
利用ldd检查一下可执行文件的链接关系,tbb链接位置正确,符合预期
这篇关于编译生成tbb动态库并用cmake链接的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!