在ROS的运行过程中,始终存在一个时间戳,这个时间戳可以用来查看代码的运行时间:
ros::Time start = ros::Time::now();
cout << start << endl;
代码串
ros::Time end = ros::Time::now();
cout << end << endl;
添加两个时间戳打印结果,单位是秒,通过两个时间戳相减可以得到这段程序的运行时间。
1)用clock()函数
#include
#include
using namespace std;
int main()
{
clock_t startTime,endTime;
startTime = clock();//计时开始
for ( int i = 0; i < 2147483640; i++)
{
i++;
}
endTime = clock();//计时结束
cout << "The run time is:" <<(double)(endTime - startTime) / CLOCKS_PER_SEC << "s" << endl;
cout << "The run time is:" << (double)clock() /CLOCKS_PER_SEC<< "s" << endl;
system("pause");
return 0;
}
输出:
The run time is:3.67578s
The run time is:3.67688s
clock函数返回进程运行时间,但是这个运行时间单位不是秒,而是CPU运行的时钟周期计数。
所以要得到消耗的时间(秒),需要除以CPU时钟频率,也就是CLOCKS_PER_SEC.以得到一个以秒为单位的数值。
printf(“%.2lf\n”,(double)clock()/CLOCKS_PER_SEC);因此以上可输出程序运行时间。
2)使用std::chrono
#include
#include
using namespace std;
int main()
{
chrono::system_clock::time_point t1 = chrono::system_clock::now();
//需测试运行时间的代码
for ( int i = 0; i < 2147483640; i++)
{
i++;
}
chrono::system_clock::time_point t2 = chrono::system_clock::now();
chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);
cout << "run time = " << time_used.count() << " seconds. " << endl;
return 0;
}
c++11的时间库chrono均位于名字空间std::chrono下,std::chrono时间的更多用法参考https://blog.csdn.net/sunlin972913894/article/details/103194920
3)使用Boost库中的timer
#include
#include
using namespace std;
int main()
{
boost::timer t;
//需测试运行时间的代码
for ( int i = 0; i < 2147483640; i++)
{
i++;
}
cout<<"运行时间:"<<t.elapsed() <<"s"<<endl;//输出已流失的时间
return 0;
}
timer类可以测量时间的流逝,是小型计时器,提供毫秒级别的计时精度。
还有其他方式获取程序运行时间,如timeGetTime()函数,暂且提供以上几种方式