【实用】几个统计代码段运行时间工具

文章介绍了在C++、ROS和Python中测量代码段运行时间的几种方法。C++中提到了使用ctime和chrono库,ROS中利用ros::Time和ros::Duration类,而Python则使用time模块的perf_counter函数。此外,还展示了在各语言中实现短暂休眠的代码示例。

为测试算法性能,经常需要记录代码段运行时间,分别给出三种方式: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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值