for循环的一种加速方法

一、源码如下:

#include "stdafx.h"
#include "cv.h"
#include "highgui.h"
#include <istream>

using namespace cv;
using namespace std; 


int _tmain(int argc, _TCHAR* argv[])
{
	Mat srcImg = imread("D:\\Documents\\Desktop\\图像拼接测试图片\\11-over750.bmp", CV_LOAD_IMAGE_GRAYSCALE);
	Mat dstImg1, dstImg2;
	srcImg.copyTo(dstImg1);
	srcImg.copyTo(dstImg2);

	uchar *srcData = srcImg.data;
	uchar *dstData1 = dstImg1.data;
	uchar *dstData2 = dstImg2.data;

	int size = srcImg.cols * srcImg.rows;
	int threshold = 122;
	int i;

	double ts1 = ( double )getTickCount();

	for(i = 0; i < size; ++i)
	{
		if(srcData[i] < threshold)
			dstData1[i] = 0;
		else
			dstData1[i] = 255;

	}//i

	double te1 = ( double )getTickCount();
	double tim1 = (te1 - ts1) * 1000.0 / getTickFrequency();

	double ts2 = ( double )getTickCount();

	i = 0;
	int size2 = size - 4;
	for(; i < size2; i += 4)
	{
		if(srcData[i] < threshold)
			dstData2[i] = 0;
		else
			dstData2[i] = 255;


		if(srcData[i + 1] < threshold)
			dstData2[i + 1] = 0;
		else
			dstData2[i + 1] = 255;


		if(srcData[i + 2] < threshold)
			dstData2[i + 2] = 0;
		else
			dstData2[i + 2] = 255;


		if(srcData[i + 3] < threshold)
			dstData2[i + 3] = 0;
		else
			dstData2[i + 3] = 255;


	}//i
	for(; i < size; ++i)
	{
		if(srcData[i] < threshold)
			dstData2[i] = 0;
		else
			dstData2[i] = 255;	
	}//i

	double te2 = ( double )getTickCount();
	double tim2 = (te2 - ts2) * 1000.0 / getTickFrequency();

	cout << "     one loop:" << tim1 << endl;
	cout << "one four loop:" << tim2 << endl;

	namedWindow("img1");
	namedWindow("img2");
	imshow("img1", dstImg1);
	imshow("img2", dstImg2);

	waitKey(0);
	return 0;
}
时间对比:

1、Debug下时间:


2、Release下时间:


结论:几乎加速一倍。

你可能感兴趣的:(C++,for,加速,程序加速)