Linux内核驱动定时微秒级别实现

Linux内核驱动定时微秒级别实现


 

复制代码
#include <linux/module.h>


#include <linux/kthread.h>


#define TIMEOUT_HR 1000000  /* 1us */
static struct hrtimer etx_hr_timer;
ktime_t ktime;


enum hrtimer_restart hrtimer_callback(struct hrtimer *timer)
{
    static int count;

    printk(KERN_INFO "hrtimer callback is running count:%d\n", count++);
    hrtimer_forward_now(timer, ktime_set(0, TIMEOUT_HR));

    return HRTIMER_RESTART;
}
static int  __init lkm_init(void)
{
    printk(KERN_INFO "init lkm module.\n");
    
    /* 设置高精度时钟 */
    ktime = ktime_set(0, TIMEOUT_HR);
    hrtimer_init(&etx_hr_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
    etx_hr_timer.function = &hrtimer_callback;
    hrtimer_start(&etx_hr_timer, ktime, HRTIMER_MODE_REL);

    return 0;

}

static void __exit lkm_exit(void)
{
    
    hrtimer_cancel(&etx_hr_timer);
    
    printk(KERN_INFO "exit lkm module.\n");
}

module_init(lkm_init);
module_exit(lkm_exit);

MODULE_VERSION("0.0");
MODULE_DESCRIPTION("sample kernel module");
MODULE_LICENSE("GPL");
MODULE_AUTHOR("panda_w");
复制代码

 

 

 

 

复制代码
    #include <time.h>
    static struct timespec time_start={0, 0},time_end={0, 0};
    unsigned long long Timesta_s, Timesta_ns,;
    clock_gettime(CLOCK_REALTIME, &time_end);
    Timesta_s  = time_end.tv_sec-time_start.tv_sec;
    Timesta_ns = time_end.tv_nsec - time_start.tv_nsec;
    clock_gettime(CLOCK_REALTIME, &time_start); 
    printf("Write_SHM  Timesta_s    =    %lluns\t Timesta_ns    =    %lluns\n\n",Timesta_s,Timesta_ns);  




复制代码

 

 

 

 

 

复制代码
#include <stdio.h>
#include <time.h>

int main (void)
{
    time_t now;
    struct tm *ptm;
    //time() returns the time as the number of seconds since the Epoch,
    //1970-01-01 00:00:00 +0000 (UTC)
    //这里只能得到当前距离某个时间的总秒数,需要进一步转换
    time (&now);
    ptm = localtime (&now);           //获取当地日期和时间
    printf ("now: %s", asctime(ptm)); //将转换后的时间以字符串形式显示

    return 0;
}
复制代码

 

 

 

 

 

 

 优质博客:

  https://blog.csdn.net/qq_37858386/article/details/85784994

 

posted @   panda_w  阅读(1438)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示