時鐘滴答(clock tick) 請問時間的嘀嗒數是根據什麼來設定的
有必要明确一些Linux核心時鐘驅動中的基本概念。
(1)時鐘周期(clock cycle)的頻率:8253/8254 PIT的本質就是對由晶體振蕩器産生的時鐘周期進行計數,晶體振蕩器在1秒時間内産生的時鐘脈沖個數就是時鐘周期的頻率。Linux用宏 CLOCK_TICK_RATE來表示8254 PIT的輸入時鐘脈沖的頻率(在PC機中這個值通常是1193180HZ),該宏定義在include/asm-i386/timex.h頭檔案中:
#define CLOCK_TICK_RATE 1193180
(2)時鐘滴答(clock tick):我們知道,當PIT通道0的計數器減到0值時,它就在IRQ0上産生一次時鐘中斷,也即一次時鐘滴答。PIT通道0的計數器的初始值決定了要過多少時鐘周期才産生一次時鐘中斷,是以也就決定了一次時鐘滴答的時間間隔長度。
(3)時鐘滴答的頻率(HZ):也即1秒時間内PIT所産生的時鐘滴答次數。類似地,這個值也是由PIT通道0的計數器初值決定的(反過來說,确定了時鐘滴答的頻率值後也就可以确定8254 PIT通道0的計數器初值)。Linux核心用宏HZ來表示時鐘滴答的頻率,而且在不同的平台上HZ有不同的定義值。對于ALPHA和IA62平台HZ的值是1024,對于SPARC、MIPS、ARM和i386等平台HZ的值都是100。該宏在i386平台上的定義如下(include/asm- i386/param.h):
#ifndef HZ
#define HZ 100
#endif
根據HZ的值,我們也可以知道一次時鐘滴答的具體時間間隔應該是(1000ms/HZ)=10ms。
times函數使用不适用于線程上取執行時間間隔。一般的時間精度為10ms,比gettimeofday低的。
==times tms_utime HandControlProcess=== 0.000000
==times tms_stime HandControlProcess=== 0.000000
==times tms_cutime HandControlProcess=== 0.000000
==times tms_cstime HandControlProcess=== 0.000000
==times tms_cstime HandControlProcess times_2-times_1=== 2000.000000
HZ=100
20.000000
#include <stdio.h>
#include <linux/time.h>
#include<sys/times.h>
#include <unistd.h>
#define CLOCKS_PER_SEC 1l
//#define _SC_CLK_TCK 100l
int main()
{
struct tms tmp;
struct tms tmp1, tmp2;
clock_t times_1, times_2;
clock_t begin = times(&tmp);
times_1 = times(&tmp1);
sleep(20);
times_2 = times(&tmp2);
printf("==times tms_utime HandControlProcess=== %lf\n", (double)(tmp2.tms_utime-tmp1.tms_utime)/1);
printf("==times tms_stime HandControlProcess=== %lf\n", (double)(tmp2.tms_stime-tmp1.tms_stime)/1);
printf("==times tms_cutime HandControlProcess=== %lf\n", (double)(tmp2.tms_cutime-tmp1.tms_cutime)/1);
printf("==times tms_cstime HandControlProcess=== %lf\n", (double)(tmp2.tms_cstime-tmp1.tms_cstime)/1);
printf("==times tms_cstime HandControlProcess times_2-times_1=== %lf\n", (double)(times_2-times_1)/1);
clock_t end = times(&tmp);
unsigned long HZ = sysconf( _SC_CLK_TCK );
printf("HZ=%ld\n", HZ);
printf("%lf\n", (double)(end-begin)/HZ );
}