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

相关文章

用python实现k近邻算法的示例代码

K近邻算法(或简称kNN)是易于理解和实现的算法,而且是你解决问题的强大工具。 什么是kNN kNN算法的模型就是整个训练数据集。当需要对一个未知数据实例进行预测时,kNN算法会在训...

Python实现的计算马氏距离算法示例

Python实现的计算马氏距离算法示例

本文实例讲述了Python实现的计算马氏距离算法。分享给大家供大家参考,具体如下: 我给写成函数调用了 python实现马氏距离源代码: # encoding: utf-8 fro...

Python使用matplotlib实现绘制自定义图形功能示例

Python使用matplotlib实现绘制自定义图形功能示例

本文实例讲述了Python使用matplotlib实现绘制自定义图形功能。分享给大家供大家参考,具体如下: 一 代码 from matplotlib.path importPath...

Python入门教程1. 基本运算【四则运算、变量、math模块等】 原创

在熟悉了Python的基本安装与环境配置之后,我们来看看Python的基本运算操作。 1. 基本运算 >>>6 # 这里的‘#'是注释符号,不参与运算 6 >...

Python实现在Linux系统下更改当前进程运行用户

在上一篇文章中,我们讲了如何在linux上用python写一个守护进程。主要原理是利用linux的fork函数来创建一个进程,然后退出父进程运行,生成的子进程就会成为一个守护进程。细心观...