写在前面的话:
- 版权声明:本文为博主原创文章,转载请注明出处!
- 博主是一个小菜鸟,并且非常玻璃心!如果文中有什么问题,请友好地指出来,博主查证后会进行更正,啾咪~~
- 每篇文章都是博主现阶段的理解,如果理解的更深入的话,博主会不定时更新文章。
- 本文初次更新时间:2020.12.10,最后更新时间:2020.12.10
正文开始
本文提供计算代码执行时间的几种方式。
环境详情:
- Windows 10
- VS 2019
- OpenCV 4.5
1. getTickCount() 和 getTickFrequency()
1.1 代码示例
OpenCV
常用getTickCount()
和getTickFrequency()
来计算程序执行时间,在OpenCV源码中也经常能看到这样的操作:
int64 t = getTickCount();
//...一通操作
cout << "xxx time" << ((getTickCount() - t) / getTickFrequency()) << "sec";
getTickCount()
返回从操作系统启动到当前所经的计时周期数,getTcikFrequency()
返回CPU
的频率(C++中单位为秒,也就是每秒重复的次数)。
所以(getTickCount() - t) / getTickFrequency()
表示(结束计时次数 - 开始计时次数) / 每秒重复次数 = 从开始到结束所用时间(s)
贴一段完整代码:
#include <opencv2/opencv.hpp>
#include <Windows.h>
using namespace cv;
using namespace std;
int main()
{
double tickStart = (double)getTickCount(); //计时开始
Sleep(3000);
double tickEnd = (double)getTickCount(); //计时结束
cout << "subTicks: " << tickEnd - tickStart << endl;
cout << "tickFrequency: " << getTickFrequency() << endl;
cout << "time: " << (tickEnd - tickStart) / (getTickFrequency()) << "s" << endl;
return 0;
}
运行结果:
subTicks: 30012147
TickFrequency: 1e+07
time: 3.00121s
1.2 函数解析
getTickCount()
getTickCount()
为opencv
中的函数,返回值为自某一时刻(比如计算机启动)开始,计算机总共经过的tick的次数。
函数原型:
int64 cv::getTickCount()
头文件:
#include <opencv2/core/utility.hpp>
详情也可【点击这里】查看:
/** @brief Returns the number of ticks.
The function returns the number of ticks after the certain event (for example, when the machine was
turned on). It can be used to initialize RNG or to measure a function execution time by reading the
tick count before and after the function call.
@sa getTickFrequency, TickMeter
*/
CV_EXPORTS_W int64 getTickCount();
顺便说一句,int64 t = getTickCount();
和double t = (double)getTickCount();
都是可以的。
getTcikFrequency()
getTickFrequency()
返回的是CPU在一秒钟内会发出的tick的次数。
函数原型:
double cv::getTickFrequency()
头文件:
#include <opencv2/core/utility.hpp>
详情也可【点击这里】查看:
/** @brief Returns the number of ticks per second.
The function returns the number of ticks per second. That is, the following code computes the
execution time in seconds:
@code
double t = (double)getTickCount();
// do something ...
t = ((double)getTickCount() - t)/getTickFrequency();
@endcode
@sa getTickCount, TickMeter
*/
CV_EXPORTS_W double getTickFrequency();
2. getTimeSec()
2.1 代码示例
getTimeSec()
返回经过的时间(以秒为单位)。
示例:
#include <opencv2/opencv.hpp>
#include <Windows.h>
using namespace cv;
using namespace std;
int main()
{
TickMeter tm;
tm.start();
Sleep(3000);
tm.stop();
cout << "Total time: " << tm.getTimeSec() << "s" << endl;
return 0;
}
运行结果:
Total time: 3.00976s
2.2 函数解析
函数原型:
double cv::TickMeter::getTimeSec() const
头文件:
#include <opencv2/core/utility.hpp>
其实可以看到,该方法跟上面的方法一毛一样。详情也可以【点击这里】:
//! returns passed time in seconds.
CV_WRAP double getTimeSec() const
{
return (double)getTimeTicks() / getTickFrequency();
}
更多可以查看类【cv::TickMeter
】