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 ", 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. "); /* 设置高精度时钟 */ 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. "); } 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 Timesta_ns = %lluns ",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