我想知道我的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负载不同,这给了我不同的结果。
在C++11中,这是一个非常容易使用的方法。 你必须使用std::chrono::high_resolution_clock
,来自<chrono>
头。
像这样使用它:
#include <iostream>
#include <chrono>
void function()
{
long long number = 0;
for( long long i = 0; i != 2000000; ++i )
{
number += 5;
}
}
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;
return 0;
}
这将测量函数的持续时间。
注意:你不会总是得到相同的函数时间。这是因为你的机器的CPU可能被电脑上运行的其他进程使用得较少或较多,就像你在解决一个数学习题时,你的大脑可能比较集中或不集中。在人类的头脑中,我们可以记住一个数学问题的解决方案,但对于计算机来说,同样的过程将永远是新的东西;因此,正如我所说的,你不会永远得到相同的结果
这里有一个函数,可以测量作为参数传递的任何函数的执行时间:
#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
简单的程序来寻找一个函数的执行时间。
#include <iostream>
#include <ctime> // time_t
#include <cstdio>
void function()
{
for(long int i=0;i<1000000000;i++)
{
// do nothing
}
}
int main()
{
time_t begin,end; // time_t is a datatype to store time values.
time (&begin); // note time before execution
function();
time (&end); // note time after execution
double difference = difftime (end,begin);
printf ("time taken for function() %.2lf seconds.\n", difference );
return 0;
}