可利用C++中的函数getTickCount()和getTickFrequency()测量代码段的运行时间。
首先要明白函数getTickCount()和函数getTickFrequency()返回值的含义。
关于函数getTickCount()和函数getTickFrequency()返回值的含义,
请参见博文 https://www.hhai.cc/thread-111-1-1.html
明白这两个函数返回值的含义后,再看下面的示例代码就很好理解了。
double begin1, end1, time1;
begin1 = (double)getTickCount();
const int ntimes = 100;
for (int i = 0; i < ntimes; i++)
{
my_function();// 待测试运行时间的代码
}
end1 = (double)getTickCount();
time1 = (end1 - begin1) / getTickFrequency();
std::cout << "time consuming:" << time1 << "s" << std::endl<<std::endl;
std::cout << "time consuming:" << 1000*time1 << "ms" << std::endl<<std::endl;
注意:
①由于上面的表达式“((double)getTickCount() - tTime)/getTickFrequency()”的运行结果是秒,所以如果要以毫秒为单位,则要乘以1000。
②测试时最好取多次测试结果的平均值,避免偶然事件造成的干扰。