-
時間:
絕對時間: 2020.6.9 23:59:59
相對時間: 時間計量取決於 參考點 相對時間 -
內核是如何計時:
int jiffies; 一開機jiffies=0, 每隔一定的時間jiffies++;
一秒鐘,jiffies累加多少次呢???
精確度(不高)
x86 1000次/s 每次1ms 1ms
ARM9 100次/s 10ms 10ms
ARM-A53 200-500次/s
不同的cpu 一秒鐘jiffies累加的次數,是不確定的.
爲了統一,內核 定義了 HZ這個宏.HZ 表示, 當前平臺,jiffies一秒鐘累加的次數.
內核的時間管理用到了 ##一個 硬件定時器###,對他進程編程,讓他一秒鐘來HZ次中斷,在中斷中jiffies++; -
計算下面的耗時: 移植,jiffies一秒鐘累加HZ次.
T1=jiffies;
do_something();
T2=jiffies;
請求 do_somethign()函數的耗時 秒/毫秒分別表示答案: (T2-T1)/HZ sec
定時器 驅動編寫
1.定義並初始化 定時器對象
struct timer_list {
unsigned long expires; 超時時間
void (*function)(unsigned long data); 方法
unsigned long data; 私有數據
};
未來時間expire
私有數據
struct timer_list timer_obj;
init_timer(struct timer_list *timer);
timer_obj.expires = xxx;
timer_obj.data = yyy;
timer_obj.function = mm_fun;
2.將定時器對象添加到 內核中
void add_timer(struct timer_list * timer);
到達指定的時間後,定時器fun被執行, 然後定時器對象被刪除.
定時器只能被執行一次
3.刪除定時器
如果定時器被執行,則自動被刪除
如果沒有被執行,則可以手工刪除
del_timer(struct timer_list *timer);
示例
/*****************************************************************
* Copyright (C) 2019 Sangfor Ltd. All rights reserved.
*
* 文件名稱:timer.c
* 創 建 者:yinfei-hu
* 創建日期:
* 功能描述:
*
*****************************************************************/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/timer.h>
struct global_data {
int No;
struct timer_list timer_obj;
};
struct global_data gstruct;
void timer_function(unsigned long data)
{
struct global_data *pt_gstruct = (struct global_data *)data;
printk("%s->%d No %d\n",__func__,__LINE__,pt_gstruct->No);
pt_gstruct->timer_obj.expires = jiffies + HZ/2;
add_timer(&pt_gstruct->timer_obj);
}
int module_fun_init(void)
{
init_timer(&gstruct.timer_obj);
gstruct.timer_obj.expires = jiffies+HZ;
gstruct.timer_obj.data = (long)&gstruct;
gstruct.timer_obj.function = timer_function;
gstruct.No = 1234;
add_timer(&gstruct.timer_obj);
printk("%s->%d\n",__FUNCTION__,__LINE__);
return 0;
}
void module_fun_exit(void)
{
del_timer(&gstruct.timer_obj);
printk("%s->%d\n",__FUNCTION__,__LINE__);
}
/* 內核模塊入口 module_init 裏面的參數,指向誰,誰就是模塊入口函數*/
module_init(module_fun_init);
/* 內核模塊出口 module_exit 裏面的參數,指向誰,誰就是模塊出口函數*/
module_exit(module_fun_exit);
/*模塊作者信息*/
MODULE_AUTHOR("YinFei.Hu <[email protected]>");
/*模塊信息*/
MODULE_DESCRIPTION(" system timer driver");
/*告訴內核願意遵守gpl協議*/
MODULE_LICENSE("GPL");