我想知道在我的c++程序中某个函数在Linux上执行需要多少时间。之后,我想做一个速度比较。我看到了几个时间函数,但最终从boost。空间:
process_user_cpu_clock, captures user-CPU time spent by the current process
现在,我不清楚如果我使用上述函数,我会得到哪个CPU在该函数上花费的唯一时间吗?
其次,我找不到任何使用上述功能的例子。请问有谁能告诉我如何使用上面的功能?
p.s.:现在,我使用std::chrono::system_clock::now()以秒为单位获得时间,但这给了我不同的结果,因为不同的CPU负载每次。
如果你想要安全的时间和代码行,你可以用一行宏来测量函数的执行时间:
a)实现如上所述的时间测量类(这是我的android实现):
class MeasureExecutionTime{
private:
const std::chrono::steady_clock::time_point begin;
const std::string caller;
public:
MeasureExecutionTime(const std::string& caller):caller(caller),begin(std::chrono::steady_clock::now()){}
~MeasureExecutionTime(){
const auto duration=std::chrono::steady_clock::now()-begin;
LOGD("ExecutionTime")<<"For "<<caller<<" is "<<std::chrono::duration_cast<std::chrono::milliseconds>(duration).count()<<"ms";
}
};
b)添加一个方便的宏,它使用当前函数名作为TAG(在这里使用宏很重要,否则__FUNCTION__将计算为MeasureExecutionTime而不是你想测量的函数
#ifndef MEASURE_FUNCTION_EXECUTION_TIME
#define MEASURE_FUNCTION_EXECUTION_TIME const MeasureExecutionTime measureExecutionTime(__FUNCTION__);
#endif
c)在你想要测量的函数的开头写你的宏。例子:
void DecodeMJPEGtoANativeWindowBuffer(uvc_frame_t* frame_mjpeg,const ANativeWindow_Buffer& nativeWindowBuffer){
MEASURE_FUNCTION_EXECUTION_TIME
// Do some time-critical stuff
}
这将导致以下输出:
ExecutionTime: For DecodeMJPEGtoANativeWindowBuffer is 54ms
请注意,这(和所有其他建议的解决方案一样)将测量函数被调用和返回之间的时间,而不一定是CPU执行函数的时间。但是,如果您不给调度程序任何更改,通过调用sleep()或类似方法来挂起正在运行的代码,则两者之间没有区别。
#include <iostream>
#include <chrono>
void function()
{
// code here;
}
int main()
{
auto t1 = std::chrono::high_resolution_clock::now();
function();
auto t2 = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
std::cout << duration<<"/n";
return 0;
}
这对我很管用。
注意:
high_resolution_clock不能在不同的标准库实现中实现一致,应该避免使用它。它通常只是std::chrono::steady_clock或std::chrono::system_clock的别名,但它是哪一个取决于库或配置。当它是system_clock时,它不是单调的(例如,时间可以倒退)。
例如,对于gcc的libstdc++,它是system_clock,对于MSVC,它是steady_clock,对于clang的libc++,它取决于配置。
通常应该直接使用std::chrono::steady_clock或std::chrono::system_clock,而不是std::chrono::high_resolution_clock:使用steady_clock测量持续时间,使用system_clock测量时钟时间。
在Scott Meyers的书中,我发现了一个通用泛型lambda表达式的例子,可以用来测量函数的执行时间。(c++ 14)
auto timeFuncInvocation =
[](auto&& func, auto&&... params) {
// get time before function invocation
const auto& start = std::chrono::high_resolution_clock::now();
// function invocation using perfect forwarding
std::forward<decltype(func)>(func)(std::forward<decltype(params)>(params)...);
// get time after function invocation
const auto& stop = std::chrono::high_resolution_clock::now();
return stop - start;
};
问题是,您只能测量一次执行,因此结果可能非常不同。为了获得可靠的结果,您应该测量大量的执行。
根据Andrei Alexandrescu在code::dive 2015会议上的演讲-编写快速代码I:
测量时间:tm = t + tq + tn + to
地点:
Tm -测量(观察)时间
T -实际感兴趣的时间
Tq -由量化噪声增加的时间
Tn -由各种噪声源添加的时间
To -开销时间(测量、循环、调用函数)
根据他在后面的演讲中所说的,你应该把大量执行中的最小值作为你的结果。
我鼓励你们去看他解释原因的那节课。
还有谷歌上的一个很好的库- https://github.com/google/benchmark。
这个库使用简单,功能强大。你可以在youtube上查看钱德勒·卡鲁斯的一些讲座,他在实践中使用了这个库。例如,2017年CppCon:钱德勒·卡鲁斯《无处可去》;
使用示例:
#include <iostream>
#include <chrono>
#include <vector>
auto timeFuncInvocation =
[](auto&& func, auto&&... params) {
// get time before function invocation
const auto& start = high_resolution_clock::now();
// function invocation using perfect forwarding
for(auto i = 0; i < 100000/*largeNumber*/; ++i) {
std::forward<decltype(func)>(func)(std::forward<decltype(params)>(params)...);
}
// get time after function invocation
const auto& stop = high_resolution_clock::now();
return (stop - start)/100000/*largeNumber*/;
};
void f(std::vector<int>& vec) {
vec.push_back(1);
}
void f2(std::vector<int>& vec) {
vec.emplace_back(1);
}
int main()
{
std::vector<int> vec;
std::vector<int> vec2;
std::cout << timeFuncInvocation(f, vec).count() << std::endl;
std::cout << timeFuncInvocation(f2, vec2).count() << std::endl;
std::vector<int> vec3;
vec3.reserve(100000);
std::vector<int> vec4;
vec4.reserve(100000);
std::cout << timeFuncInvocation(f, vec3).count() << std::endl;
std::cout << timeFuncInvocation(f2, vec4).count() << std::endl;
return 0;
}
编辑:
当然,你总是需要记住,你的编译器可以优化或不优化某些东西。像perf这样的工具在这种情况下很有用。
下面是一个函数,它将测量作为参数传递的任何函数的执行时间:
#include <chrono>
#include <utility>
typedef std::chrono::high_resolution_clock::time_point TimeVar;
#define duration(a) std::chrono::duration_cast<std::chrono::nanoseconds>(a).count()
#define timeNow() std::chrono::high_resolution_clock::now()
template<typename F, typename... Args>
double funcTime(F func, Args&&... args){
TimeVar t1=timeNow();
func(std::forward<Args>(args)...);
return duration(timeNow()-t1);
}
使用示例:
#include <iostream>
#include <algorithm>
typedef std::string String;
//first test function doing something
int countCharInString(String s, char delim){
int count=0;
String::size_type pos = s.find_first_of(delim);
while ((pos = s.find_first_of(delim, pos)) != String::npos){
count++;pos++;
}
return count;
}
//second test function doing the same thing in different way
int countWithAlgorithm(String s, char delim){
return std::count(s.begin(),s.end(),delim);
}
int main(){
std::cout<<"norm: "<<funcTime(countCharInString,"precision=10",'=')<<"\n";
std::cout<<"algo: "<<funcTime(countWithAlgorithm,"precision=10",'=');
return 0;
}
输出:
norm: 15555
algo: 2976