首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >用Python实现高精度时钟

用Python实现高精度时钟
EN

Stack Overflow用户
提问于 2018-05-30 05:03:34
回答 2查看 0关注 0票数 0

有没有一种方法可以用Python来测量时间?-比1秒更精确?我怀疑是否有一种跨平台的方法可以做到这一点;我对Unix上的高精度时间很感兴趣,特别是在SunSPARC机器上运行的Solaris。

时差似乎能够进行高精度的时间测量,但与其测量代码片段所需的时间,我更希望直接访问时间值。

EN

回答 2

Stack Overflow用户

发布于 2018-05-30 13:57:02

可以简单地使用标准time模块:

>>> import time
>>> time.time()        #return seconds from epoch
1261367718.971009      

计时一段代码:

start = time.time()
#your code to measure time
print(str((time.time() - start )*1000.0) + "milliseconds")

精度time.time()浮点数因操作系统而异:

对于linux和mac,精度是+-1微秒或0.001毫秒。

Windows用户+-16毫秒精度由于时钟实现问题,因为进程中断。用于windows高精度时钟使用。timeit或者不是基于窗户时钟的东西。

票数 0
EN

Stack Overflow用户

发布于 2018-05-30 14:51:50

Python试图使用最精确的时间函数来实现您的平台。time.time()

/* 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 */
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100004613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档