【问题标题】:python time measure for every function [duplicate]每个函数的python时间测量[重复]
【发布时间】:2014-11-15 12:04:34
【问题描述】:

我刚刚在 python 中完成了我的第一个程序的编写,我已经在一个模块中编写了我的所有函数,我只是通过将输入文件作为参数从命令行执行它并且它起作用了。但是当我给一个大数据集时,我的程序连续运行了一段时间。现在我的下一步是找出在我的模块中哪个函数花费了更多时间。我可以得到整个程序所花费的时间,但我需要分别为每个功能。

我试图理解 python 中的 timeit 和 profile 模块,但根据我的理解,它们给出了特定函数所花费的时间。有没有办法知道我模块中每个函数所花费的时间作为统计数据(一次全部)?

提前致谢。

【问题讨论】:

标签: python performance python-3.x time


【解决方案1】:

在终端,运行

python -m profile -s time file.py

python -m cProfile -s time file.py

第二个可以更快,而且永远不会更糟。

这将给出如下内容:

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
       39    0.132    0.003    0.139    0.004 :0(load_dynamic)
      239    0.097    0.000    0.097    0.000 :0(loads)
    541/1    0.083    0.000    3.556    3.556 :0(exec)
       30    0.082    0.003    0.082    0.003 :0(statusBar)
                        ... etc ...

左侧将包含您的函数。

【讨论】:

  • 我收到这些错误 --> 文件 "/usr/lib/python3.4/runpy.py",第 170 行,在 _run_module_as_main "main", mod_spec) 文件中“/usr/lib/python3.4/runpy.py”,第 85 行,在 _run_code exec(code, run_globals) 文件中“/usr/lib/python3.4/profile.py”,第 589 行,在 main () 文件“/usr/lib/python3.4/profile.py”,第 575 行,在主代码中 = compile(fp.read(), progname, 'exec') 文件“/home/****/eclipseworkspace /abcd.py", 第 20 行打印 '%r (%r, %r) %2.2f sec' % \
  • 如果你只运行python file.py会发生什么?
  • 另外,python -V 说什么?它应该以“Python 2”开头。
  • 我有 2.7 和 3.4.0 作为我的 ubuntu 14 版本的一部分。所以我将默认版本更改为 Python 3.4.0
  • 对,所以您需要运行 python2 -m profile -s time file.py,因为您的代码是 Python 2。print '%r (%r, %r) %2.2f sec' 是 Python 2 语法。
【解决方案2】:

首先我建议使用profilers 模块或timeit 来实现此目标。timeit 提供了一种简单的方法来为少量 Python 代码计时!

要分析接受单个参数的函数,您可以这样做:

import cProfile
import re
cProfile.run('re.compile("foo|bar")')

您也可以像这样使用Decorator 来测量专用方法的执行时间:

import time                                                

def measure_time(f):

  def timed(*args, **kw):
    ts = time.time()
    result = f(*args, **kw)
    te = time.time()

    print '%r (%r, %r) %2.2f sec' % \
          (f.__name__, args, kw, te-ts)
    return result

return timed

你可以这样使用它:

  @measure_time
  def foo():
        #content of function 

注意f.__name__ 返回函数的名称! (在本例中为“foo”)

【讨论】:

  • 对不起,我以前从未这样做过。所以,我必须在程序的最开始添加这个 measure_time 函数,并在我的每个函数之前添加 @measure_time ?我说的对吗?
  • 整个程序可以使用profile或者timeit吗?这会给我每个函数花费的时间,还是我必须使用它们来查找一个函数花费的时间一次?
  • 您需要在 .py 中定义函数并在任何函数之前使用 @measure_time 来查找这些运行时!
  • 最好使用配置文件,您可以将其用于所有代码
  • 要分析一个接受单个参数的函数,你可以这样做:import cProfile import re cProfile.run('re.compile("foo|bar")')
猜你喜欢
  • 2011-07-25
  • 1970-01-01
  • 2014-10-04
  • 1970-01-01
  • 2014-04-27
  • 2018-06-09
  • 2010-12-13
  • 1970-01-01
相关资源
最近更新 更多