linux用户空间获得ns纳秒级时间示例

2025-05-27 0 37

一、引言
我们在测试程序的性能的时候往往需要获得ns级的精确时间去衡量一个程序的性能,下面介绍下linux中用户空间获得ns级时间的方法

二、用户空间获得ns级时间
使用clock_gettime函数,函数原型如下:

long sys_clock_gettime (clockid_t which_clock, struct timespec *tp);

1.which_clock参数解释

CLOCK_REALTIME:系统实时时间,随系统实时时间改变而改变,即从UTC1970-1-1 0:0:0开始计时,中间时刻如果系统时间被用户该成其他,则对应的时间相应改变

CLOCK_MONOTONIC:从系统启动这一刻起开始计时,不受系统时间被用户改变的影响

CLOCK_PROCESS_CPUTIME_ID:本进程到当前代码系统CPU花费的时间

CLOCK_THREAD_CPUTIME_ID:本线程到当前代码系统CPU花费的时间

2.struct timespec结构

复制代码

代码如下:


struct timespec
{
time_t tv_sec;
long int tv_nsec;
};

使用范例代码如下:

复制代码

代码如下:


#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(void)
{
struct timespec time_start={0, 0},time_end={0, 0};
clock_gettime(CLOCK_REALTIME, &time_start);
printf("start time %llus,%llu ns\\n", time_start.tv_sec, time_start.tv_nsec);
clock_gettime(CLOCK_REALTIME, &time_end);
printf("endtime %llus,%llu ns\\n", time_end.tv_sec, time_end.tv_nsec);
printf("duration:%llus %lluns\\n", time_end.tv_sec-time_start.tv_sec, time_end.tv_nsec-time_start.tv_nsec);
return 0;
}

编译命令:

复制代码

代码如下:


gcc test.c -o test -lrt

运行结果:

复制代码

代码如下:


./test
start time 1397395863s,973618673 ns
endtime 1397395863s,973633297 ns
duration:0s 14624ns

从运行结果可以看出 调用printf()函数一次需要15us左右。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 linux用户空间获得ns纳秒级时间示例 https://www.kuaiidc.com/65307.html

相关文章

发表评论
暂无评论