须要提升工程运行效率,将里面多个环节进行同步处理。可是在网上找了几个demo以后,发现调用复杂的库(future等)和模块用到的库可能存在潜在的冲突,结果future好像和tensorRT冲突,thread好像和openGL冲突。存在一些问题。试来试去,仍是最简单的thread比较好使,openGL的问题留给之后解决吧。linux
//g++ -o mu test.cpp -std=c++11 -lpthread #include <iostream> #include <string> #include <unistd.h> #include <vector> #include <thread> #include"time.h" class xx { private: int s, n; public: std::vector<int> out; std::vector<bool> status; int dd; /*用两个元素的vector实现轮询的处理*/ xx() { s = 0, n = 0, dd = 0; for (int i = 0; i < 2; i++) { out.push_back(0); status.push_back(false); } std::cout << "dd: " << dd << ";" << std::endl; } /*运行时间4ms起,用它表示主代码耗时*/ void get() { n = (n + 1) % 2; dd = out[n]; out[n] = 0; status[n] = false; std::cout << "s:" << s << " ;dd: " << dd << " ;n: " << n << ";" << std::endl; usleep(4000);//4 ms } /*能够插入时提醒*/ bool check() { int nn = s; for (int i = 0; i < 2; i++) { if (!status[nn]) { return true; } nn = (nn + 1) % 2; } return false; } /*6ms,用它表示前处理*/ void run() { usleep(6000);//6 ms int nn = (s + 1) % 2; if (!status[nn]) { s = (s + 1) % 2; out[s] = 5; status[s] = 1; } else { printf("pass is %d", s); } } }; /*linux没有此函数,这是网上别人加了个壳实现的*/ unsigned long GetTickCount() { // https://blog.csdn.net/guang11cheng/article/details/6865992 struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (ts.tv_sec * 1000 + ts.tv_nsec / 1000000); } int main() { xx *yy = new xx(); float ms = 0; int N = 100; /*顺序执行耗时*/ unsigned long t1 = GetTickCount(); for (int i = 0; i < N; i++) { yy->run(); yy->get(); } unsigned long t2 = GetTickCount(); std::cout << "ordering excute eclipse: " << t2 - t1 << "ms\n"; /*lambda函数*/ auto detectionReprocess = [&]() { yy->run(); }; /*异步执行耗时*/ t1 = GetTickCount(); std::thread dataPreparation(detectionReprocess); for (int i = 0; i < N; i++) { dataPreparation.join(); dataPreparation = std::thread(detectionReprocess); yy->get(); } t2 = GetTickCount(); std::cout << "threading eclipse: " << t2 - t1 << "ms\n"; /*最后新建的thread须要join,不然报错*/ dataPreparation.join(); yy->get(); }
ordering excute eclipse: 1083ms threading eclipse: 659ms