/* Implement floattime() for various platforms */
static double
floattime(void)
{
/* There are three ways to get the time:
(1) gettimeofday() -- resolution in microseconds
(2) ftime() -- resolution in milliseconds
(3) time() -- resolution in seconds
In all cases the return value is a float in seconds.
Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
fail, so we fall back on ftime() or time().
Note: clock resolution does not imply clock accuracy! */
#ifdef HAVE_GETTIMEOFDAY
{
struct timeval t;
#ifdef GETTIMEOFDAY_NO_TZ
if (gettimeofday(&t) == 0)
return (double)t.tv_sec + t.tv_usec*0.000001;
#else /* !GETTIMEOFDAY_NO_TZ */
if (gettimeofday(&t, (struct timezone *)NULL) == 0)
return (double)t.tv_sec + t.tv_usec*0.000001;
#endif /* !GETTIMEOFDAY_NO_TZ */
}
#endif /* !HAVE_GETTIMEOFDAY */
{
#if defined(HAVE_FTIME)
struct timeb t;
ftime(&t);
return (double)t.time + (double)t.millitm * (double)0.001;
#else /* !HAVE_FTIME */
time_t secs;
time(&secs);
return (double)secs;
#endif /* !HAVE_FTIME */
}
}
# measure the smallest time delta by spinning until the time changes
def measure():
t0 = time.time()
t1 = t0
while t1 == t0:
t1 = time.time()
return (t0, t1, t1-t0)
samples = [measure() for i in range(10)]
for s in samples:
print s
Python努力使用最精确的时间函数来实现
time.time()
:(来自http://svn.python.org/view/python/trunk/Modules/timemodule.c?revision=81756&view=markup)
大卫的帖子试图显示Windows上的时钟分辨率是多少。我被他的输出搞糊涂了,所以我写了一些代码,显示我的Windows 8 x64笔记本电脑上的
time.time()
分辨率为1毫秒:哪些输出:
还有一种方法,对delta进行1000个样本的平均值:
两次连续运行时的输出:
所以我的Windows 8 x64上的
time.time()
分辨率是1毫秒。对
time.clock()
执行类似的运行将返回0.4微秒的分辨率:返回:
即~
0.4e-06
关于
time.clock()
的一个有趣的事情是,它返回自第一次调用该方法以来的时间,因此如果您想要微秒分辨率的墙时间,可以执行以下操作:(这可能会在一段时间后漂移,但您可以偶尔更正,例如
dc > 3600
将每小时更正一次)标准的
time.time()
函数提供亚秒精度,尽管精度因平台而异。对于Linux和Mac,精度为+-
1微秒或0.001毫秒。由于进程中断导致的时钟实现问题,Windows上的Python使用了16毫秒的精度。如果要测量执行时间,timeit
模块可以提供更高的分辨率。Python 3.7为
time
模块引入了新的函数,这些函数提供了更高的分辨率:相关问题 更多 >
编程相关推荐