Python time模块

来源:互联网 发布:淘宝王者荣耀充值便宜 编辑:程序博客网 时间:2024/05/16 06:17

1.sleep()

Python 编程中使用 time 模块可以让程序休眠,具体方法是time.sleep(秒数),其中”秒数”以秒为单位,可以是小数,0.1秒则代表休眠100毫秒。

from time import sleepi = 1while i <= 3:    print i # 输出i    i += 1    time.sleep(1) # 休眠1秒

2.ctime( )

ctime() 函数把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。 如果参数未给或者为None的时候,将会默认time.time()为参数。它的作用相当于 asctime(localtime(secs))。

print "time.ctime() : %s" % time.ctime()#time.ctime() : Wed Jul 29 13:06:32 2015

3.clock( )

Python time clock() 函数以浮点数计算的秒数返回当前的CPU时间。用来衡量不同程序的耗时,比time.time()更有用。

这个需要注意,在不同的系统上含义不同。在UNIX系统上,它返回的是”进程时间”,它是用秒表示的浮点数(时间戳)。而在WINDOWS中,第一次调用,返回的是进程运行的实际时间。而第二次之后的调用是自第一次调用以后到现在的运行时间。(实际上是以WIN32上QueryPerformanceCounter()为基础,它比毫秒表示更为精确)

#!/usr/bin/pythonimport timedef procedure():    time.sleep(2.5)# measure process timet0 = time.clock()procedure()print time.clock() - t0, "seconds process time"# measure wall timet0 = time.time()procedure()print time.time() - t0, "seconds wall time"输出:0.0 seconds process time2.50023603439 seconds wall time
0 0