低分辨率定時(shí)器是用jiffies來定時(shí)的,所以會(huì)受到HZ影響,如果HZ為200,代表每秒種產(chǎn)生200次中斷,那一個(gè)jiffies就需要5毫秒,所以精度為5毫秒。
如果精度需要達(dá)到納秒級(jí)別,則需要使用高精度定時(shí)器hrtimer。
使用示例
單次定時(shí)
加載驅(qū)動(dòng)一秒后輸出“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");
循環(huán)定時(shí)
循環(huán)定時(shí)可以在回調(diào)函數(shù)中調(diào)用hrtimer_forward_now()
重新設(shè)置定時(shí)時(shí)間,然后將返回值設(shè)置為HRTIMER_RESTART
代表重啟定時(shí)器,就可以做到循環(huán)定時(shí)的效果。
每隔一秒輸出“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));//重新設(shè)置定時(shí)時(shí)間
return HRTIMER_RESTART;//重啟定時(shí)器
}
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
+關(guān)注
關(guān)注
87文章
11341瀏覽量
210133 -
定時(shí)器
+關(guān)注
關(guān)注
23文章
3255瀏覽量
115173 -
函數(shù)
+關(guān)注
關(guān)注
3文章
4345瀏覽量
62867
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
![](https://file1.elecfans.com/web2/M00/85/8B/wKgaomRmM5GAVbQ4AAGrDj-iw-8882.png)
#硬聲創(chuàng)作季 #Linux 學(xué)Linux-2.18.1 高精度延時(shí)實(shí)驗(yàn)-GPT定時(shí)器原理-2
GPT高精度延時(shí)定時(shí)器簡介
長時(shí)間高精度定時(shí)器
![長時(shí)間<b class='flag-5'>高精度</b><b class='flag-5'>定時(shí)器</b>](https://file1.elecfans.com//web2/M00/A4/46/wKgZomUMM3WAYrUFAAHTdFB4e5Y502.jpg)
Linux時(shí)間子系統(tǒng)中的高精度定時(shí)器(HRTIMER)的原理和實(shí)現(xiàn)
LINUX內(nèi)核定時(shí)器(高精度&低精度)
詳解高精度定時(shí)器與高級(jí)控制定時(shí)器
Linux驅(qū)動(dòng)開發(fā)高精度定時(shí)器的精度測量評(píng)測
工程師筆記|高精度定時(shí)器的同步功能
高精度定時(shí)器與高級(jí)控制定時(shí)器 PWM 封波后再恢復(fù)的區(qū)別
![<b class='flag-5'>高精度</b><b class='flag-5'>定時(shí)器</b>與高級(jí)控制<b class='flag-5'>定時(shí)器</b> PWM 封波后再恢復(fù)的區(qū)別](https://file1.elecfans.com/web2/M00/A4/9E/wKgaomUD58mAUywTAADbtBLKvFo028.png)
評(píng)論