linux定时测量
linux内核完成两种定时测量:
1.(时钟)保存当前的时间和日期--时钟电路同时用于跟踪当前时间和产生精确的时间度量。
2.(定时器)维持定时器--定时器电路由内核编程,所以它们以固定的、预先定义的频率发出中断。
本文转自:http://blog.csdn.net/jiebaoabcabc/article/details/37883167
一、linux定时测量分类:
1、实时时钟(RTC)
RTC实时时钟(Real-Time Clock),说穿了所谓RTC仅仅是一个可以连续计数的计数器,这个计数器可以预先配置为固定频率单位的累进脉冲。
RTC模块在有供电的情况下可以连续不断的计数,为其他电路持续提供实时的时钟信息。
而Linux内核对RTC的唯一用途就是把RTC用作“离线”或“后台”的时间与日期维护器。当Linux内核启动时,它从RTC中读取时间与日期的基准值。然后再运行期间内核就完全抛开RTC,从而以软件的形式维护系统的当前时间与日期,并在需要时将时间回写到RTC芯片中。所以,RTC时钟只是个为后面我们介绍的那些时钟起一个初始化的作用,仅此而已!
2、时间戳计数器(TSC)
用来记录系统节拍产生次数,系统开始工作后,掌管系统的时间。
3、可编程间隔定时器(PIT)
系统对PIT进行编程,在设定的节拍下记到规定次数后产生定时器中断。
二、linux定时器计数变量:
1.xtime变量
xtime内核变量存放当前时间和日期,它在系统初始化时被RTC附上初值,然后在系统运行过程中不断进行累加,保持与当前时间保持同步。
它是由timespec结构来描述的,可以提供纳秒级别的时间刻度。
struct timespec {
long ts_sec;
long ts_nsec;
};
xtime由/kernel/time/timekeeping.c维护。
/**
* do_gettimeofday - Returns the time of day in a timeval
* @tv: pointer to the timeval to be set
*
* NOTE: Users should be converted to using getnstimeofday()
*/
void do_gettimeofday(struct timeval *tv)
{
struct timespec now;
getnstimeofday(&now);
tv->tv_sec = now.tv_sec;
tv->tv_usec = now.tv_nsec/1000;
}
/**
* getnstimeofday - Returns the time of day in a timespec
* @ts: pointer to the timespec to be set
*
* Returns the time of day in a timespec.
*/
void getnstimeofday(struct timespec *ts)
{
struct timekeeper *tk = &timekeeper;
unsigned long seq;
s64 nsecs = 0;
WARN_ON(timekeeping_suspended);
do {
seq = read_seqbegin(&tk->lock);
ts->tv_sec = tk->xtime_sec;
nsecs = timekeeping_get_ns(tk);
} while (read_seqretry(&tk->lock, seq));
ts->tv_nsec = 0;
timespec_add_ns(ts, nsecs);
}
系统调用gettimeofday通过getnstimeofday获取时间,getnstimeofday 又通过xtime获取时间。
例:
#include <stdio.h>
#include <sys/time.h> // timeval gettimeofday
int main(void)
{
struct timeval tv;
gettimeofday(&tv, NULL);
printf("%ld %ld\n", tv.tv_sec, tv.tv_usec);
return 0;
}
2.jiffies变量
jiffies内核变量用来记录自系统启动以来产生的节拍次数。
jiffies是一个有可能溢出的32位变量,jiffies_64这个64位版本的jiffies变量基本没有溢出的可能,但是开销会比32位变量大。
/include/linux/jiffies.h对此进行如下声明:
/*
*The 64-bit value is not atomic - you MUST NOT read it
*without sampling the sequence number in xtime_lock.
*get_jiffies_64() will do this for you as appropriate.
*/
extern u64 __jiffy_data jiffies_64;
extern unsigned long volatile __jiffy_datajiffies;
三、linux定时器的使用:
1.alarm闹钟
#include<unistd.h>
unsigned int alarm(unsigned int seconds);
函数功能:创建一