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

yipeiwu_com5年前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程序设计有所帮助。

相关文章

python 统计一个列表当中的每一个元素出现了多少次的方法

如下所示: #coding=utf-8 #方式一 print('*'*20 + '方式一' + '*'*20) li1 = [1,2,2,3,3,3,4,4,4,4,5,5,5,5,...

OpenCV3.0+Python3.6实现特定颜色的物体追踪

OpenCV3.0+Python3.6实现特定颜色的物体追踪

一、环境 win10、Python3.6、OpenCV3.x;编译器:pycharm5.0.3 二、实现目标 根据需要追踪的物体颜色,设定阈值,在视频中框选出需要追踪的物体。 三、实现步...

linux系统使用python获取cpu信息脚本分享

linux系统使用python获取cpu信息脚本分享

linux系统使用python获取cpu信息脚本分享 复制代码 代码如下:#!/usr/bin/env Pythonfrom __future__ import print_functi...

django基于存储在前端的token用户认证解析

django基于存储在前端的token用户认证解析

一.前提 首先是这个代码基于前后端分离的API,我们用了django的framework模块,帮助我们快速的编写restful规则的接口 前端token原理: 把(token=加密后的...

解读python如何实现决策树算法

数据描述 每条数据项储存在列表中,最后一列储存结果 多条数据项形成数据集 data=[[d1,d2,d3...dn,result], [d1,d2,d3...dn,resul...