主要使用了基本的parallel_for的用法,按照师兄的版本修改了自己的字符识别函数,师兄新建了一个类作为一个容器,里面承载了一个用于字符识别类的指针,具体原因据师兄说是因为在并行化的时候会新建多个类的实例,所以传送一个指针,在并行类之外新建一次类的实例即可,代码如下:
#include <QtCore/QCoreApplication>
#include "patternMatch.h"
#include <tbb\concurrent_vector.h>
#include <tbb\tbb.h>
#include <tbb\scalable_allocator.h>
#include <array>
//using namespace cv;
using namespace tbb;
class paralellRecognize {
public:
patternMatch *recognizeCore;
cv::Mat *allFrame;
paralellRecognize(patternMatch* newRecognize, cv::Mat* newlist)
{
recognizeCore = newRecognize;
allFrame = newlist;
}
void operator()(const blocked_range<long>& r) const {
cv::Mat* a = allFrame;
for (long i = r.begin(); i != r.end(); ++i){
//cout << "frame index" << " " << i << endl;
recognizeCore->RecognizeOneImage(i);
}
}
~paralellRecognize(){
}
};
阴影显示的即为关键处,在main函数中的代码:
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
cv::Mat *mat = NULL;
patternMatch *newRecognize = new patternMatch(4, 1986); // 实例化一次,4和1984是表示当前视频有4行,1986帧,测试方便而使用了具体的数
int totalFileNum = newRecognize->GetFileNum();
// 非并行版本
tick_count t0 = tick_count::now(); // tick_count是tbb中自带计算函数运行时间的类型,很好用哦
newRecognize->startMatch();
tick_count t1 = tick_count::now();
// 并行版本
tick_count t2 = tick_count::now();
parallel_for(blocked_range<long>(0, totalFileNum), paralellRecognize(newRecognize, mat));
tick_count t3 = tick_count::now();
printf("serial work took %g seconds\n", (t1 - t0).seconds());
printf("parallel work took %g seconds\n", (t3 - t2).seconds());
double serialTime = (t1 - t0).seconds();
double parallelTime = (t3 - t2).seconds();
printf("ratio for two timt: %f\n", serialTime / parallelTime);
// 打印结果至txt文件
newRecognize->printText();
printf("Write file completed.\n");
return a.exec();
}
其次是release发布程序的时候,需要tbb.dll,我使用的是win32模式的release,所以应该使用的是32位版本的,我电脑中所在目录为C:\Program Files (x86)\Intel\Composer XE 2015\redist\ia32\tbb\vc12,如果是64位的话,应该在C:\Program Files (x86)\Intel\Composer XE 2015\redist\intel64\tbb中选择相应的tbb.dll文件。否则会出现无法运行exe程序,应用程序无法正常启动0xc000007b之类的问题。