天天看点

Linux运行了多久?&&gettimeofday()的用法

(1)查看时钟中断:

$ cat /proc/interrupts

           CPU0

  0:    1380471    IO-APIC-edge  timer

  1:       3626       IO-APIC-edge  i8042

  7:          0          IO-APIC-edge  parport0

  8:          3          IO-APIC-edge  rtc

  9:          1          IO-APIC-level  acpi

 14:      39229     IO-APIC-edge  libata

 15:      39999     IO-APIC-edge  libata

169:     244640   IO-APIC-level  uhci_hcd:usb2

177:          2        IO-APIC-level  uhci_hcd:usb1, ehci_hcd:usb5

185:          0        IO-APIC-level  uhci_hcd:usb3

193:     410350   IO-APIC-level  uhci_hcd:usb4, [email protected]:0000:00:02.0

201:     251593   IO-APIC-level  Intel ICH7

209:     148723   IO-APIC-level  eth0

NMI:          0

LOC:    1380276

ERR:          0

MIS:          0

第一列就是时钟中断号,第二列表示中断次数,第四列是时钟源名称。由于时钟中断是有一定频率的,那么根据这个值可以知道系统运行了多久。时钟中断的频率在Linux中称为节拍tick。用下面这个命令查看当前系统配置的节拍数,在自己的ubuntu下执行:

$cd /boot;

$cat config-2.6.28-17-generic|grep '^CONFIG_HZ',回显:

$CONFIG_HZ=250

一秒有250个时钟中断,那么运行了1380471/250=5521.88s。补充说明:

A,cat /proc/interrupts在我自己的ubuntu里面运行,会显示两个CPU结果(双核),但中断次数固定在163,由此怀疑此方法是不是不适合双核电脑。

B,在ubuntu系统中,/boot的目录下的config-2.6.28-17-generic是系统的宏定义配置文件,相当于MID上的autoconf.h。

C,管道的应用也即在前面cat的文件结果中搜寻带特定字符串的语句,如果不带^,则在结果中会把#屏蔽的语句一起显示。

(2)查看/proc文件:

$ cat        /proc/uptime

5863.73     4889.31

第一个数值表示系统总启动时间,第二个数值表示系统空闲时间,单位都是秒。空闲比例为4889.31/5863.73=83.38%,还是比较闲的。

(3)uptime命令:

$ uptime

17:12:47 up  1:38,  8 users,  load average: 0.94, 0.51, 0.47

分别表示分别表示该指令启动时刻、状态、系统已运行总时间、用户数、过去1、5、15分钟的负载平衡。

(4)通过gettimeofday获取系统时间,首先熟悉下面结构体

struct timeval {

       time_t      tv_sec;    

      suseconds_t tv_usec;   

};

timeval表示一个时间点,比如:timeval.tv_sec = 1   (s),timevat.tv_usec = 500 000 (μs),则1s500000μs = 1.5s。注意:millisecond 毫秒;microsecond 微秒。一个实例如下:

[cpp]  view plain copy

  1. #include <stdio.h>  
  2. #include <sys/time.h>  
  3. #include <time.h>  
  4. int main(int argc, char * argv[]){  
  5.     struct timeval tv;                //(1)  
  6.     while(1){  
  7.         gettimeofday(&tv, NULL);      //(2)  
  8.         printf("time %u:%u\n", tv.tv_sec, tv.tv_usec);  
  9.         sleep(2);  
  10.     }  
  11.     return 0;  
  12. }  

每隔两秒显示系统时间。结果是:

Linux运行了多久?&amp;&amp;gettimeofday()的用法

参考原文:http://blog.csdn.net/blackbillow/archive/2009/01/23/3850170.aspx

参考原文: http://hi.baidu.com/zengzhaonong/item/9a3fff2f92b82bd50e37f950

继续阅读