Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
655 views
in Technique[技术] by (71.8m points)

linux - Python: How to get number of mili seconds per jiffy

I'd like to know the HZ of the system, i.e. how many mili seconds is one jiffy from Python code.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is USER_HZ

>>> import os
>>> os.sysconf_names['SC_CLK_TCK']
2
>>> os.sysconf(2)
100

which is what the kernel uses to report time in /proc.

From the time(7) manual page:

The Software Clock, HZ, and Jiffies

The accuracy of various system calls that set timeouts, (e.g., select(2), sigtimedwait(2)) and measure CPU time (e.g., getrusage(2)) is limited by the resolution of the software clock, a clock maintained by the kernel which measures time in jiffies. The size of a jiffy is determined by the value of the kernel constant HZ.

The value of HZ varies across kernel versions and hardware platforms. On i386 the situation is as follows: on kernels up to and including 2.4.x, HZ was 100, giving a jiffy value of 0.01 seconds; starting with 2.6.0, HZ was raised to 1000, giving a jiffy of 0.001 seconds. Since kernel 2.6.13, the HZ value is a kernel configuration parameter and can be 100, 250 (the default) or 1000, yielding a jiffies value of, respec‐ tively, 0.01, 0.004, or 0.001 seconds. Since kernel 2.6.20, a further frequency is available: 300, a number that divides evenly for the com‐ mon video frame rates (PAL, 25 HZ; NTSC, 30 HZ).

The times(2) system call is a special case. It reports times with a granularity defined by the kernel constant USER_HZ. Userspace applica‐ tions can determine the value of this constant using sysconf(_SC_CLK_TCK).

If you absolutely must know SYSTEM_HZ:

>>> from ctypes import *
>>> rt = CDLL('librt.so')
>>> CLOCK_REALTIME = 0
>>> class timespec(Structure):
...     _fields_ = [("tv_sec", c_long), ("tv_nsec", c_long)]
... 
>>> res = timespec()
>>> rt.clock_getres(CLOCK_REALTIME, byref(res))
0
>>> res.tv_sec, res.tv_nsec
(0, 4000250)
>>> SYSTEM_HZ = round(1/(res.tv_sec + (res.tv_nsec/10.0**9)))

Gives 250 on my laptop (which sounds about right) and 1000000000 in a VM…


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...