• python计算程序运行时间


    内置模块time包含很多与时间相关函数。我们可通过它获得当前的时间和格式化时间输出。

    time(),以浮点形式返回自Linux新世纪以来经过的秒数。在linux中,00:00:00 UTC, January 1, 1970是新**49**的开始。

    import time
    
    start = time.clock()
    
    #当中是你的程序
    
    elapsed = (time.clock() - start)
    print("Time used:",elapsed)


    或者:
    from time import time
    
    def timeTest():
        start = time()
        print("Start: " + str(start))
        for i in range(1, 100000000):
            pass
        stop = time()
        print("Stop: " + str(stop))
        print(str(stop-start) + "")
    
    def main():
        timeTest()
    
    if __name__=='__main__':
        main()

    Python:time.clock() vs. time.time()

    作者 Ross Wan on 2008/09/19

    有时候,我们需要知道程序或者当中的一段代码的执行速度,于是就会加入一段计时的代码,如下:

    start = time.clock()
    ... do something
    elapsed = (time.clock() - start)

    又或者

    start = time.time()
    ... do something
    elapsed = (time.time() - start)

    那究竟 time.clock() 跟 time.time(),谁比较精确呢?带着疑问,查了 Python 的 time 模块文档,当中 clock() 方法有这样的解释:

    clock()

    On
    Unix, return the current processor time as a floating point number
    expressed in seconds. The precision, and in fact the very definition of
    the meaning of “processor time”, depends on that of the C function of
    the same name, but in any case, this is the function to use for
    benchmarking Python or timing algorithms.

    On Windows, this
    function returns wall-clock seconds elapsed since the first call to
    this function, as a floating point number, based on the Win32 function
    QueryPerformanceCounter(). The resolution is typically better than one
    microsecond.

    可见,time.clock() 返回的是处理器时间,而因为 Unix 中 jiffy 的缘故,所以精度不会太高。clock转秒,除以1000000。

    总结

    究竟是使用 time.clock() 精度高,还是使用 time.time() 精度更高,要视乎所在的平台来决定。总概来讲,在 Unix 系统中,建议使用 time.time(),在 Windows 系统中,建议使用 time.clock()。

    这个结论也可以在 Python 的 timtit 模块中(用于简单测量程序代码执行时间的内建模块)得到论证:

    if sys.platform == "win32":
    # On Windows, the best timer is time.clock()
    default_timer = time.clock
    else:
    # On most other platforms the best timer is time.time()
    default_timer = time.time

    使用 timeit 代替 time,这样就可以实现跨平台的精度性:

    start = timeit.default_timer()
    ... do something
    elapsed = (timeit.default_timer() - start)


  • 相关阅读:
    rpm包的管理
    多态应用实例--制作饮品
    纯虚函数和抽象类
    rpm包的管理
    动态监控进程
    封装继承和多态
    计网面试题
    模拟浏览器加载页面时的版本下载
    xpath中extract()使用
    MVC+EF CODE FIRST的使用
  • 原文地址:https://www.cnblogs.com/youxin/p/3157099.html
Copyright © 2020-2023  润新知