为了账号安全,请及时绑定邮箱和手机立即绑定

time.time 和time.clock 有什么差别?

import time

from functools import reduce

def performance(f):

    def fn(*args, **kw):


        a1 = time.time()

        t1 = time.clock()

        r = f(*args, **kw)

        t2 = time.clock()

        a2 = time.time()

        print('call %s() in %fs' % (f.__name__,(t2 - t1)))

        print('test time.time: %fs' % (a2 - a1))

        return r

    return fn

print('*'*20)

@performance

def factorial(n):

    return reduce(lambda x,y: x*y, range(1, n+1))

print(factorial(10000))



正在回答

1 回答

一,两个函数的文档:

1,time.time():

time.time()  

Return
 the time in seconds since the epoch as a floating point number. Note 
that even though the time is always returned as a floating point number,
 not all systems provide time with a better precision than 1 second. 
While this function normally returns non-decreasing values, it can 
return a lower value than a previous call if the system clock has been 
set back between the two calls.

time.time()  

返回从(1970.1.1)至今的秒数。虽然这个函数的返回值永远为浮点数,但并不是所有系统提供的秒数都会精确到小数点以后。一般情况下这个函数的返回值不会小于它上一次被调用的返回值,除非在两次调用之间发生了重置。

2,time.clock():

time.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 中,将当前的处理器时间以浮点数的形式返回,单位为秒。它的精确度(准确地说是“处理器时间”的精确度)取决于同名的C函数,无论如何,这个函数是python关于时间计算的标尺。

WINDOWS中,第一次调用,返回的是进程运行的实际时间。而第二次之后的调用是自第一次调用以后到现在的运行时间。(实际上是以WIN32上QueryPerformanceCounter()为基础,它比表示更为精确)

二,用法及总结
1,在Windows中,time.clock()更精确;
2,这两个函数不可以混合使用
2 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
python进阶
  • 参与学习       255533    人
  • 解答问题       3038    个

学习函数式、模块和面向对象编程,掌握Python高级程序设计

进入课程

time.time 和time.clock 有什么差别?

我要回答 关注问题
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号