python中 time.clock() time.time()如何使用【面试题详解】

今天爱分享给大家带来python中 time.clock() time.time()如何使用【面试题详解】,希望能够帮助到大家。
哪一个更适合于计时? 哪个更精确,

例如


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

and

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

区别


clock() -> floating point number

Return the CPU time or real time since the start of the process or since
the first call to clock().
This has as much precision as the system records.

time() -> floating point number

Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.

根据 time module doc


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.

简而言之, time.clock()更精确些, 但是如果涉及cpu外的硬件时间统计(e.g. gpu), 只能使用time.time()

另外基于性能的评估, 可以去看下timeit模块

人已赞赏
Python

python中如何获取当前时间【面试题详解】

2020-12-28 21:35:29

Python

为什么Python的'private'方法并不是真正的私有方法【面试题详解】

2020-12-28 21:38:33

'); })();