Linux内核中获取纳秒时间戳的方法

本文介绍了两种在Linux内核4.14.216版本中获取纳秒时间戳的方法:方法1是使用getnstimeofday64,方法2则是利用ktime_get_real_ns。这两种方法都适用于衡量内核函数执行时间。

1 方法1:使用getnstimeofday64方法

此处以获取内核中mm/page_alloc.c__alloc_pages_direct_reclaim函数中的__perform_reclaim函数的执行之间为例(内核版本4.14.216),代码如下:

/* The really slow allocator path where we enter direct reclaim */
static inline struct page *
__alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
                             unsigned int alloc_flags, const struct alloc_context *ac,
                             unsigned long *did_some_progress)
{
	struct page *page = NULL;
    bool drained = false;
    struct timespec64 start, end;
	
	getnstimeofday64(&start);
    *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
    getnstimeofday64(&end);
    printk("func : %s-> %s, time spent = %ld s, %ld ns\n", \
    	__func__, "__perform_reclaim", (end.tv_sec - start.tv_sec),\
    	(end.tv_nsec - start.tv_nsec));
   
   //... the rest of the code
}

2 方法2:使用ktime_get_real_ns方法

此处仍是以获取内核中mm/page_alloc.c__alloc_pages_direct_reclaim函数中的__perform_reclaim函数的执行之间为例(内核版本4.14.216),代码如下:

/* The really slow allocator path where we enter direct reclaim */
static inline struct page *
__alloc_pages_direct_reclaim(gfp_t gfp_mask, unsigned int order,
                             unsigned int alloc_flags, const struct alloc_context *ac,
                             unsigned long *did_some_progress)
{
	struct page *page = NULL;
    bool drained = false;
    u64 start_time, end_time;
	
	start_time = ktime_get_real_ns();
    *did_some_progress = __perform_reclaim(gfp_mask, order, ac);
    end_time = ktime_get_real_ns();
    printk("func : %s-> %s, time spent = %ld ns\n", \
    	__func__, "__perform_reclaim", (end_time - start_time));
   
   //... the rest of the code
}

相关参考:
Linux latest timekeeping

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值