我有此代码段,可在程序(C ++和OpenCV)中的任何地方使用。用于计时一些操作:
double t;
// Some code...
t = (double)getTickCount();
Object1.LotOfComputing();
t = 1000*((double)getTickCount() - t)/getTickFrequency();
cout << "Time for LotOfComputing =" << t << " milliseconds."<< endl;
cout << "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" << endl;
这是OpenCV文档建议对函数/部分代码进行计时的方式,在使用了几周后,它似乎对我有用。我测量的时间范围从大约1毫秒到700毫秒,我将它们四舍五入到毫秒。
问题是我在程序中花费了很多不同的操作,并且这些代码片段使代码混乱。
我想知道将这些代码行放入函数中是否明智,例如:
double timing(double time){
timing = 1000*((double)getTickCount() - time)/getTickFrequency();
cout << "Time for LotOfComputing =" << timing << " milliseconds."<< endl;
cout << "=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=" << endl;
return timing;
}
所以我可以使用它:
double t;
// Some code...
t = (double)getTickCount();
Object1.LotOfComputing();
timing(t);
我只是担心通过函数调用的执行时间...也许我只是担心什么!
基本上,它会为每个作用域(例如一对{})创建静态计数器,这些计数器在模块启动时初始化,并在模块释放时读取。当然,这也要花费时间,因此您不希望在某个紧密循环内发生这种情况。
// you might want to change the clock
#define get_ticks cv::getTickCount
#define get_freq cv::getTickFrequency
double dt(int64 t) { return double(t*1000/get_freq())/1000.0; }
struct Profile
{
string name;
int64 t; // accumulated time
int64 c; // function calls
Profile(const string & name)
: name(name)
, t(0)
, c(0)
{}
~Profile()
{
cerr << format("%-24s %8u ",name.c_str(),c);
cerr << format("%13.6f ",dt(t/c));
cerr << format("%13.6f ",dt(t));
cerr << format("%14u",t);
cerr << endl;
}
struct Scope
{
Profile & p;
int64 t;
Scope(Profile & p)
: p(p)
, t(get_ticks())
{}
~Scope()
{
int64 t1 = get_ticks();
if ( t1 > t )
{
p.t += t1 - t;
p.c ++;
}
}
};
};
#define PROFILEX(s) static Profile _a_rose(s); Profile::Scope _is_a_rose_is(_a_rose);
#define PROFILE PROFILEX(__FUNCTION__)
void foo() {
PROFILE;
int k=10;
while (k) {
PROFILEX("foo while loop");
k --;
}
}
void bar() {
PROFILE;
}
int main() {
PROFILE;
{
PROFILEX("useless scope");
bar();
bar();
}
foo();
return 0;
}
foo while loop 10 0.000000 0.000002 3959
foo 1 0.000007 0.000007 13000
bar 2 0.000000 0.000000 843
useless scope 1 0.000004 0.000004 7710
main 1 0.000017 0.000017 31712
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句