测试矩阵连续运算的速度问题的代码

float r = 0.0f;
RNG rng(1);

double t1 = (double)getTickCount();
for (size_t i = 0; i < 10000; i++)
{
	Mat a, b, c;
	a = Mat::ones(512, 512, CV_32FC1);
	a = a * rng.uniform(0.0f, 100.0f);
	b = Mat::ones(512, 512, CV_32FC1);
	b = b * rng.uniform(0.0f, 100.0f);
	c = Mat::ones(512, 512, CV_32FC1);
	c = c * rng.uniform(0.0f, 100.0f);
	Mat d = (a.mul(b) + c)*1000.f;
	int x = 511 * rng.uniform(0.0f, 1.0f);
	int y = 511 * rng.uniform(0.0f, 1.0f);
	r = r + d.at<float>(x, y);
}
t1 = (double)getTickCount() - t1;

std::cout << "compute time :" << t1*1000.0 / cv::getTickFrequency() << " ms \n";
cout << r << endl;
r = 0.0f;

double t2 = (double)getTickCount();
for (size_t i = 0; i < 10000; i++)
{
	cv::Mat a, b, c;
	a = Mat::ones(512, 512, CV_32FC1);
	a = a * rng.uniform(0.0f, 100.0f);
	b = Mat::ones(512, 512, CV_32FC1);
	b = b * rng.uniform(0.0f, 100.0f);
	c = Mat::ones(512, 512, CV_32FC1);
	c = c * rng.uniform(0.0f, 100.0f);
	Mat d = a.mul(b);
	d = d + c;
	d = d*1000.f;
	int x = 511 * rng.uniform(0.0f, 1.0f);
	int y = 511 * rng.uniform(0.0f, 1.0f);
	r = r + d.at<float>(x, y);
}
t2 = (double)getTickCount() - t2;

std::cout << "compute time :" << t2*1000.0 / cv::getTickFrequency() << " ms \n";
cout << r << endl;
r = 0.0f;

double t3 = (double)getTickCount();
for (size_t i = 0; i < 10000; i++)
{
	cv::Mat a, b, c;
	a = Mat::ones(512, 512, CV_32FC1);
	a = a * rng.uniform(0.0f, 100.0f);
	b = Mat::ones(512, 512, CV_32FC1);
	b = b * rng.uniform(0.0f, 100.0f);
	c = Mat::ones(512, 512, CV_32FC1);
	c = c * rng.uniform(0.0f, 100.0f);
	Mat d = a.mul(b);
	d += c;
	d *= 1000.f;
	int x = 511 * rng.uniform(0.0f, 1.0f);
	int y = 511 * rng.uniform(0.0f, 1.0f);
	r = r + d.at<float>(x, y);
}
t3 = (double)getTickCount() - t3;

std::cout << "compute time :" << t3*1000.0 / cv::getTickFrequency() << " ms \n";
cout << r << endl;

上面的计算复杂度是一样的。
实验证明,第二种方式最快,矩阵表达式计算要尽量展开,并且不要使用*=或+=等简化编程。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值