【openMP】在Qt Creator中使用 Eigen和openMP
參考連結:
1、https://blog.csdn.net/tigerisland45/article/details/54150950
2、https://blog.csdn.net/gengshenghong/article/details/7003110
1、首先配置.pro 檔案,以下是我的控制檯(console).pro。注意紅色部分。
QT += core
QT -= gui
CONFIG += c++11
TARGET = testEigenProcess
CONFIG += console
CONFIG -= app_bundle
TEMPLATE = app
SOURCES += main.cpp
# The following define makes your compiler emit warnings if you use
# any feature of Qt which as been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if you use deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0
INCLUDEPATH += \
/home/david/MySoft/myeigen
QMAKE_CXXFLAGS += -fopenmp
LIBS += -fopenmp
2、程式碼示例如下:
//#define the EIGEN_USE_MKL_ALL
#include <QCoreApplication>
#include <Eigen/Dense>
#include <iostream>
#include <time.h>
#include <omp.h>
using namespace Eigen;
using namespace std;
void print_xiao(char i)
{
cout << "omp_get_num_threads : " << omp_get_num_threads() << endl;
cout << "omp_get_max_threads: " << omp_get_max_threads() << endl;
cout << "omp_get_thread_num: " << omp_get_thread_num() << endl;
cout << i << endl;
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
initParallel();
// use openMP
cout << "before set openMP threads: " << omp_get_num_threads() << endl;
int set_thread = 10;
omp_set_num_threads(set_thread);
cout << "after set openMP threads: " << omp_get_num_threads() << endl;
#pragma omp parallel for
for (char i = 'a'; i <= 'z'; i++)
print_xiao(i);
// test mult-threading
int mat_size = 1000;
MatrixXd matXd, save_mat;
clock_t time_start = 0, time_end = 0;
matXd.resize(mat_size, mat_size);
matXd.setIdentity();
//#pragma omp parallel for
for(int i = 0; i < 10;i++)
{
time_start = clock();
// save_mat = matXd.inverse();
save_mat = matXd * matXd;
// cout << save_mat << endl;
time_end = clock();
cout <<i << " -> Elapsed time is "
<< (double)(time_end - time_start)/CLOCKS_PER_SEC<< " seconds." << endl;
}
return a.exec();
}
很多有趣的現象,開啟多執行緒後你會發現Eigen矩陣相乘變慢啦、。。。。。。。。哎