低分辨率定时器是用jiffies来定时的,所以会受到HZ影响,如果HZ为200,代表每秒种产生200次中断,那一个jiffies就需要5毫秒,所以精度为5毫秒。
如果精度需要达到纳秒级别,则需要使用高精度定时器hrtimer。
使用示例
单次定时
加载驱动一秒后输出“hrtimer handler
”:
#include < linux/init.h >
#include < linux/kernel.h >
#include < linux/module.h >
#include < linux/ktime.h >
#include < linux/hrtimer.h >
static struct hrtimer timer;
static enum hrtimer_restart timer_handler(struct hrtimer *timer )
{
printk("hrtimer handlern");
return HRTIMER_NORESTART;
}
static int __init my_init(void)
{
ktime_t tim;
hrtimer_init(&timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
timer.function = timer_handler;
tim = ktime_set(1,0); //1s
hrtimer_start(&timer,tim,HRTIMER_MODE_REL);
return 0;
}
static void __exit my_exit(void)
{
printk("%s entern", __func__);
hrtimer_cancel(&timer);
}
module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
循环定时
循环定时可以在回调函数中调用hrtimer_forward_now()
重新设置定时时间,然后将返回值设置为HRTIMER_RESTART
代表重启定时器,就可以做到循环定时的效果。
每隔一秒输出“hrtimer handler
”:
#include < linux/init.h >
#include < linux/kernel.h >
#include < linux/module.h >
#include < linux/ktime.h >
#include < linux/hrtimer.h >
static struct hrtimer timer;
static enum hrtimer_restart timer_handler(struct hrtimer *timer )
{
printk("hrtimer handlern");
hrtimer_forward_now(timer, ktime_set(1,0));//重新设置定时时间
return HRTIMER_RESTART;//重启定时器
}
static int __init my_init(void)
{
ktime_t tim;
hrtimer_init(&timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
timer.function = timer_handler;
tim = ktime_set(1,0); //1 s
hrtimer_start(&timer,tim,HRTIMER_MODE_REL);
return 0;
}
static void __exit my_exit(void)
{
printk("%s entern", __func__);
hrtimer_cancel(&timer);
}
module_init(my_init);
module_exit(my_exit);
MODULE_LICENSE("GPL");
声明:本文内容及配图由入驻作者撰写或者入驻合作网站授权转载。文章观点仅代表作者本人,不代表电子发烧友网立场。文章及其配图仅供工程师学习之用,如有内容侵权或者其他违规问题,请联系本站处理。
举报投诉
-
Linux
+关注
关注
87文章
11030浏览量
207269 -
定时器
+关注
关注
23文章
3186浏览量
112711 -
函数
+关注
关注
3文章
4142浏览量
61553
发布评论请先 登录
相关推荐
![](https://file1.elecfans.com/web2/M00/83/14/wKgZomRl1jGAHa7sAAAV9FDk9nQ371.png)
![](https://file1.elecfans.com/web2/M00/85/8B/wKgaomRmM5GAVbQ4AAGrDj-iw-8882.png)
![](https://file1.elecfans.com/web2/M00/85/8B/wKgaomRmM5GAaNAHAAGuVORrBM8481.png)
Linux时间子系统中的高精度定时器(HRTIMER)的原理和实现
虽然大部分时间里,时间轮可以实现O(1)时间复杂度,但是当有进位发生时,不可预测的O(N)定时器级联迁移时间,这对于低分辨率定时器来说问题不大,可是它大大地影响了定时器的精度;
发表于 05-10 14:11
•7508次阅读
LINUX内核定时器(高精度&低精度)
linux从内核2.6.16开始引入了高精度定时器,达到ns级别。自此,内核拥有两套并行计时器,低精度和高精度。如果
发表于 05-13 09:41
•3969次阅读
Linux驱动开发高精度定时器的精度测量评测
前言 今天我们来评测linux内核的高精度定时器。顺便利用通过Tektronix示波器 和 DS100 Mini 数字示波器进行交叉测试。 因项目需要用到精准的时间周期,所以要评估它的可行性,并验证
Linux驱动高精度定时器hrtimer
高分辨率定时器( hrtimer )以 ktime_t 来定义时间, 精度可以达到纳秒级别 , ktime_t 定义如下: typedef s64 ktime_t ; 可以用 ktime_set
评论