Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3843898
  • 博文数量: 146
  • 博客积分: 3918
  • 博客等级: 少校
  • 技术积分: 8584
  • 用 户 组: 普通用户
  • 注册时间: 2010-10-17 13:52
个人简介

个人微薄: weibo.com/manuscola

文章分类

全部博文(146)

文章存档

2016年(3)

2015年(2)

2014年(5)

2013年(42)

2012年(31)

2011年(58)

2010年(5)

分类: LINUX

2013-08-31 22:57:01

   内核时钟的频率是由CONFIG_HZ决定的,以前默认是100HZ,现在内核默认是250HZ。而1个jiffy是1个时钟滴答,时间间隔是有CONFIG_HZ决定的,频率是250HZ,也就是周期为4ms。每4ms,增加一个时钟滴答,也即jiffies++。
   原理比较简单,如何查看自己的Linux的CONFIG_HZ的值呢?  
  1. root@manu:~/code/c/self/ticks# grep ^CONFIG_HZ /boot/config-3.2.0-29-generic-pae
  2. CONFIG_HZ_250=y
  3. CONFIG_HZ=250
    有意思的是,systemtap tutorial有个比较好玩的实验,也可以确定CONFIG_HZ的大小。  

  1. global count_jiffies, count_ms
  2. probe timer.jiffies(100) { count_jiffies ++ }
  3. probe timer.ms(100) { count_ms ++ }
  4. probe timer.ms(543210)
  5. {
  6.     hz=(1000*count_jiffies) / count_ms
  7.     printf ("jiffies:ms ratio %d:%d => CONFIG_HZ=%d\n",
  8.     count_jiffies, count_ms, hz)
  9.     exit ()
  10. }
    输出如下:
  1. jiffies:ms ratio 1358:5420 => CONFIG_HZ=250
    实验等待的时间有点久,需要等待543210ms,9分钟左右,时间越久,误差越小,如果等待的时间段一些,会出现误差。感兴趣的筒子自行实验。
   除此外,还有一个值是USER_HZ,不了解这个的,可能会了解times系统调用,这个系统调用是统计进程时间消耗的,
  1.     #include <sys/times.h>

  2.        clock_t times(struct tms *buf);
    times系统调用的时间单位是由USER_HZ决定的,所以,times系统调用统计的时间是以10ms为单位的。说100HZ空口无凭,如何获取USER_HZ。  
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<unistd.h>
  4. #include<sys/times.h>
  5. #include<time.h>

  6. int main()
  7. {
  8.     int user_ticks_per_second ;
  9.     user_ticks_per_second = (int)sysconf(_SC_CLK_TCK);
  10.     if(user_ticks_per_second == -1)
  11.     {
  12.         fprintf(stderr,"failed to get ticks per second by sysconf\n");
  13.         return -1;
  14.     }

  15.     printf("The Number of USER ticks per second is %d\n",user_ticks_per_second);

  16.     return 0;
  17. }
    输出如下:  
  1. The Number of USER ticks per second is 100
    如果你嫌用C代码调用SYSCONF太麻烦了,可以通过shell命令getconf获得USER_HZ的值:    
  1. root@manu:~/code/c/self/ticks# getconf CLK_TCK
  2. 100
    times系统调用来统计进程信息我不建议使用了,精度太低了。提出这个USER_HZ,只是希望不要困惑,为什么CONFIG_HZ是250,而sysconf(_SC_CLK_TCK)却是100.

参考文献:
1  man 7 time
2  systemtap tutorial
阅读(17231) | 评论(2) | 转发(3) |
给主人留下些什么吧!~~

Bean_lee2013-09-02 09:16:16

dyli2000:阿Bean,能否讲讲是什么原因促使你去研究这两个值的?

最近在学习Linux时间管理。这一块,一直总是不清楚,而学习Linux时间管理的原因,是因为微博上,GFree_Wind 高峰提了问题:

内核的xtime精度是基于jiffies的,那么为什么还要提供纳秒级的数值呢?又是如何计算或者维护纳秒级的时间呢? @manuscola @Godbach @raof01 @我不是飞鱼 讨论讨论

很遗憾,和Godbach这些大牛相比,我完全插不上话,因为自己不了解。所以就开始学习时间管理这块内容了,看了三天,有不少收获了。

回复 | 举报

dyli20002013-09-02 08:41:44

阿Bean,能否讲讲是什么原因促使你去研究这两个值的?