如何正确测量计算时间?
变体 1:
std::chrono::time_point<std::chrono::system_clock> start, end;
float elapsed = 0;
int N = 100;
for(int i=0; i<N; ++i)
{
start = std::chrono::system_clock::now();
func();//target function
end = std::chrono::system_clock::now();
elapsed += std::chrono::duration_cast<std::chrono::microseconds>(end-start).count();
}
变体 2:
start = std::chrono::system_clock::now();
for(int i=0; i<N; ++i)
func();
end = std::chrono::system_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::microseconds>(end-start).count();
这些变体显示出非常不同的结果:我试图用 std::function 替换虚函数:
struct Base
{
virtual void f() = 0;
};
struct Der1 : public Base
{
virtual void f() override
{
int i=0;
for(int j=0; j<100; ++j)
i += 2*j;
}
};
struct Der2 : public Base
{
virtual void f() override
{
int i=0;
for(int j=0; j<100; ++j)
i += 3*j;
}
};
struct Base_
{
Base_(std::function<void()> f_) : f(f_) {}
std::function<void()> f;
};
struct Der1_ : public Base_
{
Der1_() : Base_([]{
int i=0;
for(int j=0; j<100; ++j)
i += 2*j;
}){}
};
struct Der2_ : public Base_
{
Der2_() : Base_([]{
int i=0;
for(int j=0; j<100; ++j)
i += 3*j;
}){}
};
void process1(std::vector<Base_*>& v)
{
for(auto &elem : v)
elem->f();
}
void process2(std::vector<Base*>& v)
{
for(auto &elem : v)
elem->f();
}
int main()
{
std::vector<Base_*> vec1;
vec1.push_back(new Der1_);
vec1.push_back(new Der2_);
vec1.push_back(new Der1_);
vec1.push_back(new Der2_);
std::vector<Base*> vec2;
vec2.push_back(new Der1);
vec2.push_back(new Der2);
vec2.push_back(new Der1);
vec2.push_back(new Der2);
std::chrono::time_point<std::chrono::system_clock> start1, end1, start2, end2;
float elapsed1 = 0;
float elapsed2 = 0;
int N = 6000;
//Variant 2
start1 = std::chrono::system_clock::now();
for(int i=0; i<N; ++i)
process1(vec1);
end1 = std::chrono::system_clock::now();
elapsed1 = std::chrono::duration_cast<std::chrono::microseconds>(end1-start1).count();
start2 = std::chrono::system_clock::now();
for(int i=0; i<N; ++i)
process2(vec2);
end2 = std::chrono::system_clock::now();
elapsed2 = std::chrono::duration_cast<std::chrono::microseconds>(end2-start2).count();
std::cout<<"virtual: "<<elapsed2<<"\npointer: "<<elapsed1;
for(int i=0; i<vec1.size(); ++i)
delete vec1[i];
for(int i=0; i<vec2.size(); ++i)
delete vec2[i];
return 0;
}
我想了解在 std::function 上替换虚函数是否能提高性能。第二个变体表示 2.5-3 增益,而第一个方法显示性能下降。