为测试算法性能,经常需要记录代码段运行时间,分别给出三种方式:cpp, Ros, python,如下所示:
C++
// 计时1:
#inlcude <ctime>
#include <time.h> //头文件2选1,建议这个
#include <iostream>
clock_t start,end;start = clock();
double dur=0;
process();
end = clock();
dur = (end - start)/CLOCKS_PER_SEC; //单位: s
cout<<"dur:"<<dur<<"s"<<endl;
// 计时2:
#include <chrono>
#include <iostream>
chrono::steady_clock::time_point t1 = chrono::steady_clock::now();
process();
chrono::steady_clock::time_point t2 = chrono::steady_clock::now();
chrono::duration<double> time_used = chrono::duration_cast<chrono::duration<double>>(t2 - t1);
cout << "solve time cost = " << time_used.count() << " seconds. " << endl;
// 计时3:【推荐】
#include <omp.h>
double start_time = omp_get_wtime();
process();
double end_time = omp_get_wtime();
std::cout << "Elapsed time: " << end_time - start_time << " seconds" << std::endl;
// 休眠1:【推荐】
#include <chrono>
#include <thread>
this_thread::sleep_for(chrono::milliseconds(1000)); // ms
// 休眠2:
#include <unistd.h>
sleep(2); // s
ROS (cpp-ROS和时间相关的操作详见连接:网页链接)
// 计时:
// ROS 中有 time 和 duration 两种类型,相应的有 ros::Time 和 ros::Duration 类
// 计算时间间隔的时候,如果两个ros::time直接作差,返回值为ros:duration
// 可使用.toSec()避免定义duration
ros::Time before_time_ = ros::Time::now();
process();
ros::Time now = ros::Time::now(); //单位: s
std::cout << "time:" << (now - before_time_).toSec()*1000 << std::endl;
before_time_ = now;
Python
#计时:
mport time
# time.clock()在python3.8已不再支持,改用time.perf_counter()
# time.perf_counter()默认单位为 s
# 获取开始时间
time_start = time.perf_counter()
# 代码段
process()
# 获取结束时间
time_end = time.perf_counter()
# 计算运行时间
run_time_s = time_end - time_start
run_time_ms = run_time * 1000
# 输出运行时间
print("运行时间:", run_time, "秒")
print("运行时间:", run_time_ms, "毫秒")
# 休眠:
import time
time.sleep(seconds)
文章介绍了在C++、ROS和Python中测量代码段运行时间的几种方法。C++中提到了使用ctime和chrono库,ROS中利用ros::Time和ros::Duration类,而Python则使用time模块的perf_counter函数。此外,还展示了在各语言中实现短暂休眠的代码示例。
2万+

被折叠的 条评论
为什么被折叠?



