Python测量程序运行时间,time.time与time.clock

Python测量程序运行时间,time.time与time.clock,第1张

现象描述:

1、time.clock 在win系统和linux系统下对相同程序的计时结果不一致

2、到底应该用什么时间计时?为什么用time.time与time.clock计时会有那么大的差异

在计算机领域有多种时间。

第一种称作CPU时间或执行时间,用于测量在执行一个程序时CPU所花费的时间。第二种称作挂钟时间,测量执行一个程序时的总时间。挂钟时间也被称作流逝时间或运行时间。与CPU时间相比,挂钟时间通常长些,因为CPU执行测量的程序可能同时还在执行其它程序的指令。

另一个重要概念是所谓的系统时间,由系统时钟测量。系统时间表示计算机系统时间传递的概念。要记住系统时钟是可以由 *** 作系统修改的,就是修改系统时间。

在Unix系统上,time.time的作用与Windows相同,但time.clock的意义不同。

在Unix系统上,time.clock以秒为单位返回当前处理器时间,例如,执行当前线程所圆好花费的CPU时间。而在Windows上,它是以秒为单位的返橘散铅回自首次调用该函数以来所流逝的系统时间。

以我遇到的Ubuntu系统上运行time.time和time.clock的例子:

time.time()显示系统时间过去大概1秒,而time.clock()显示花费在当前进程上的CPU时间只有于1毫秒。

而win下time.time()和time.clock()显示系统时间都是大致过去了1秒

在测量程序准确性能时应该使用哪一个呢?

这要视情况而定。如果程序运行的系统能够提供足够的资源给程序,例如,一个运行基于Python的web应用程序的web服务器,则使用time.clock()来测量程序会更有意义,因这个web应用程序可能是服务器上的主要程序 。如果程序运行的系统上还同时运行着其它大量程序,则使用time.time()进行测量会更有意义。 如果不是这样,就应该使用基于挂钟的计时器来测量程序的性能,因为这样通常能反应程序的环境。

放结掘桥论,一般情况下:

1、win用time.clock或time.time

2、linux 下用time.time  或 datetime.datetime.now().timestamp()

【1】(重要)https://blog.csdn.net/ao985438294363006/article/details/101349790    Python测量时间,用time.time还是time.clock 

单细胞中各种同类工具层出不重,往往需要比较软件间的重现性,运行速度等,因此查阅了python中程序运逗槐郑行时间计算的各种方法。

程序中主要有两种明历时间CPU time和Wall time, 前者山颂就是CPU实际运行的时间,包含系统CPU time和程序CPU time;

用歼迅团python实现计时器功能,代码如下:

''' Simple Timing Function.

This function prints out a message with the elapsed time from the

previous call. It works with most Python 2.x platforms. The function

uses a simple trick to store a persistent variable (clock) without

using a global variable.

'''

import time

def dur( op=None, clock=[time.time()] ):

if op != None:

duration = time.time() - clock[0]

print '%s finished. Duration %.6f seconds.' % (op, duration)

clock[0] = time.time()

# Example

if __name__ == '__main__'氏橘昌侍:

import array

dur() # Initialise the timing clock

opt1 = array.array('H')

for i in range(1000):

for n in range(1000):

opt1.append(n)

dur('Array from append')

opt2 = array.array('H')

seq = range(1000)

for i in range(1000):

opt2.extend(seq)

dur('Array from list extend')

opt3 = array.array('H')

seq = array.array('H', range(1000))

for i in range(1000):

opt3.extend(seq)

dur('Array from array extend')

# Output:

# Array from append finished. Duration 0.175320 seconds.

# Array from list extend finished. Duration 0.068974 seconds.

# Array from array extend finished. Duration 0.001394 seconds.


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/yw/12418366.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-25
下一篇 2023-05-25

发表评论

登录后才能评论

评论列表(0条)

保存