python实现简单的计时器功能函数

yipeiwu_com5年前Python基础

本文实例讲述了python实现简单的计时器功能函数。分享给大家供大家参考。具体如下:

此函数通过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.

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python异常处理例题整理

Python异常处理例题整理

什么是异常? 异常是Python对象,表示一个错误。当Python脚本发生异常时我们需要捕获处理它,否则程序会终止执行。在程序运行过程中,总会遇到各种各样的错误,有的错误是程序编写有问题...

Python numpy.zero() 初始化矩阵实例

那就废话不多说,直接上代码吧! new_array = np.zeros((107,4))# 共107行 每行4列 初值为0 >>> new_array = np...

python文件读写并使用mysql批量插入示例分享(python操作mysql)

复制代码 代码如下:# -*- coding: utf-8 -*-'''Created on 2013年12月9日 @author: hhdys''' import osimport m...

Python实现获取某天是某个月中的第几周

找了半天竟然没找到,如何在Python的datetime处理上,获取某年某月某日,是属于这个月的第几周。 无奈之下求助同学,同学给写了一个模块。【如果你知道Python有这个原生的库,请...

python 判断linux进程,并杀死进程的实现方法

如下所示: ''' @author: Jacobpc ''' import os import sys import subprocess def get_process_id(...