获取程序段执行时间
struct timeval pre_time, now_time;
unsigned int time;
gettimeofday(&pre_time, NULL);
要测试的程序段
gettimeofday(&now_time, NULL);
time = (now_time.tv_sec - pre_time.tv_sec) * 1000000;
time += now_time.tv_usec;
time -= pre_time.tv_usec;
printf("pass time = %d [us]\n", time);
这是错误的
/* * start_stop : 0 start,1 stop * distinguish: used to distinguish each other */ void print_time(int start_stop, int distinguish) { uint64_t diff_time, diff_sec, diff_usec; static struct timeval pre_time, now_time; if(!start_stop) { pre_time.tv_sec = 0; pre_time.tv_usec = 0; now_time.tv_sec = 0; now_time.tv_usec = 0; gettimeofday(&pre_time, NULL); } else { gettimeofday(&now_time, NULL); diff_sec = now_time.tv_sec - pre_time.tv_sec; diff_usec = now_time.tv_usec - pre_time.tv_usec; diff_time = (diff_sec * 1000000 + diff_usec) / 1000; dbg_printf("[%d]: diff_time=%lu ms\n", distinguish, diff_time); } }
这是错误的!
/* * start_stop : 0 start,1 stop * distinguish: used to distinguish each other */ void print_time(int start_stop, int distinguish) { uint32_t diff_time, diff_sec, diff_usec; static struct timeval pre_time, now_time; if(!start_stop) { pre_time.tv_sec = 0; pre_time.tv_usec = 0; now_time.tv_sec = 0; now_time.tv_usec = 0; gettimeofday(&pre_time, NULL); } else { gettimeofday(&now_time, NULL); diff_sec = now_time.tv_sec - pre_time.tv_sec; diff_usec = now_time.tv_usec - pre_time.tv_usec; diff_time = diff_sec * 1000 + diff_usec / 1000; dbg_printf("[%d]: diff_time=%d ms\n", distinguish, diff_time); } }
/* * start_stop : 0 start,1 stop * distinguish: used to distinguish each other */ void print_time(int start_stop, int distinguish) { uint64_t diff_time, diff_sec, diff_usec; static struct timeval pre_time, now_time; if(!start_stop) { pre_time.tv_sec = 0; pre_time.tv_usec = 0; now_time.tv_sec = 0; now_time.tv_usec = 0; gettimeofday(&pre_time, NULL); } else { gettimeofday(&now_time, NULL); diff_sec = now_time.tv_sec - pre_time.tv_sec; diff_usec = now_time.tv_usec > pre_time.tv_usec ? now_time.tv_usec - pre_time.tv_usec : pre_time.tv_usec - now_time.tv_usec ; diff_time = (diff_sec * 1000000 + diff_usec) / 1000; dbg_printf("[%d]: diff_time=%lu ms\n", distinguish, diff_time); } }
这个比较好用:
#define print_log_with_time(fmt, args...) \ do { \ struct timespec ts; \ clock_gettime(CLOCK_MONOTONIC,&ts); \ fprintf(stderr,"[%5lu.%06lu] initsvscripts %s:%d: " fmt "\n", \ ts.tv_sec, ts.tv_nsec / 1000, __func__, __LINE__, ##args); \ } while (0)
posted on 2017-12-17 23:17 Hello-World3 阅读(239) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!