Python中统计函数运行耗时的方法

yipeiwu_com6年前Python基础

本文实例讲述了Python中统计函数运行耗时的方法。分享给大家供大家参考。具体实现方法如下:

import time
def time_me(fn):
  def _wrapper(*args, **kwargs):
    start = time.clock()
    fn(*args, **kwargs)
    print "%s cost %s second"%(fn.__name__, time.clock() - start)
  return _wrapper
#这个装饰器可以在方便地统计函数运行的耗时。
#用来分析脚本的性能是最好不过了。
#这样用:
@time_me
def test(x, y):
  time.sleep(0.1)
@time_me
def test2(x):
  time.sleep(0.2)
test(1, 2)
test2(2)
#输出:
#test cost 0.1001529524 second
#test2 cost 0.199968431742 second

另一个更高级一点的版本是:

import time
import functools
def time_me(info="used"):
  def _time_me(fn):
    @functools.wraps(fn)
    def _wrapper(*args, **kwargs):
      start = time.clock()
      fn(*args, **kwargs)
      print "%s %s %s"%(fn.__name__, info, time.clock() - start), "second"
    return _wrapper
  return _time_me
@time_me()
def test(x, y):
  time.sleep(0.1)
@time_me("cost")
def test2(x):
  time.sleep(0.2)
test(1, 2)
test2(2)

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

相关文章

Python3自动签到 定时任务 判断节假日的实例

不废话,直接上代码Python3.6 签到代码,只需修改url,账号,密码即可,此处是登录时无验证登录,有验证码的自行补充 # -*- coding:utf-8 -*- imp...

Python矩阵常见运算操作实例总结

本文实例讲述了Python矩阵常见运算操作。分享给大家供大家参考,具体如下: python的numpy库提供矩阵运算的功能,因此我们在需要矩阵运算的时候,需要导入numpy的包。 一.n...

Windows下Python3.6安装第三方模块的方法

Windows下Python3.6安装第三方模块的方法

一、 官网下载安装包:  官网网址:https://www.python.org/  我下载的是3.6.3版本,如下图:    二、 安装安装包...

python中设置超时跳过,超时退出的方式

在工作中遇到过 个问题 执行一条代码时间过长 而且还不报错,卡死在那。还要继续执行下面代码,如何操作。 下面是个简单的实例 pip安装 第三方eventlet这个包 – pip inst...

Python打开文件、文件读写操作、with方式、文件常用函数实例分析

Python打开文件、文件读写操作、with方式、文件常用函数实例分析

本文实例讲述了Python打开文件、文件读写操作、with方式、文件常用函数。分享给大家供大家参考,具体如下: 打开文件: 在python3中,打开文件的函数是: open(file,...