【问题标题】:How to find the statistics and execution times of the code in python如何在python中查找代码的统计信息和执行时间
【发布时间】:2012-11-02 16:13:53
【问题描述】:

我正在研究 python,遇到了一些查找代码的统计信息和执行时间的概念

假设我有以下代码

from time import gmtime, strftime
import timeit


def calculation():
     a = 2
     b = 3
     res = a + b
     return  res

if 'name' == 'main' :
    exec_time = timeit.timeit(calculation)
    print exec_time

结果:

0.2561519145965576

所以从上面的代码中我可以找到代码的执行时间,但是如何在python中找到代码的统计信息?

最后我的意图是低于点

  1. 如何在python中找到代码的统计数据
  2. 如何在python中找到整个代码的执行时间
  3. 代码统计的真正含义是什么?

编辑代码:

例如我在文件test.py中有上面的代码

现在我已经用下面的命令运行了上面的文件

python -m cProfile test.py

结果:

sh-4.2$ python -m cProfile test.py
         4 function calls in 0.001 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.001    0.001    0.001    0.001 test.py:1(<module>)
        1    0.000    0.000    0.000    0.000 timeit.py:105(Timer)
        1    0.001    0.001    0.001    0.001 timeit.py:53(<module>)
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

所以当我运行上面的代码时我需要这样的东西,我正在尝试在文件test.py 中编写打印统计信息的功能,而不是从终端使用命令python -m cProfile test.py 运行文件。

至少我想在文件运行时找到函数calculation() 的统计信息和执行时间,因为实际上函数计算具有执行某些操作的大功能。

【问题讨论】:

  • “代码统计”是什么意思?
  • 您可能需要profiling(这是进一步研究的关键词)。另请查看the docs 和this question。
  • @chris:这实际上是我的疑问,我不知道为什么它被否决了,我对此表示怀疑并接近了 SO
  • 我编辑了我的代码,任何人都可以在上面查看....

标签: python statistics execution-time


【解决方案1】:

我想你是在问如何在代码中使用cProfile。事实证明这很容易。 cProfile.Profile 有两个未记录的方法,enable 和 disable,可用于启动和停止分析器。这意味着您可以轻松创建上下文管理器或装饰器。以下配方在一个对象中实现了这两种方法,并包含一种使用 pstat 模块处理和打印输出的方法。

import cProfile, pstats, functools

class profile:

    def __init__(self, filename=None):
        """
        If defined, output is written to *filename*, otherwise it
        is processed using *pstats* and printed to STDOUT.
        """
        self._filename = filename
        self._prof = cProfile.Profile()

    def __enter__(self):
        self._prof.enable()

    def __exit__(self, exc_type, exc_value, traceback):
        self._prof.disable()
        if self._filename is not None:
            self._prof.dump_stats(self._filename)
        else:
            stats = pstats.Stats(self._prof)
            self.print_stats(stats)

    def print_stats(self, stats):
        """
        This method processes the stats and prints them.
        """
        stats.strip_dirs().sort_stats('cumulative').print_stats(20)

    def __call__(self, func):
        self._func = func
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            with self:
                return func(*args, **kwargs)
        return wrapper

所以用法是:

@profile()
def calculation():
    a = 2
    b = 3
    res = a + b
    return  res

calculation()

或

with profile('output_file.pstat'):
    calculation()

您可以根据需要更改print_stats 以显示您想要的输出。

【讨论】:

    【解决方案2】:

    看来您要问的是如何使用 timeit 模块的编程接口。这是记录在here。您需要一个样本集来计算统计数据,例如最小值、最大值、平均值等,这意味着通过 timeit 模块中包含的 Timeit 类的 repeat 方法运行多次计算。

    例如:

    timer = timeit.Timer(calculation)
    results = timer.timeit(10000)
    

    【讨论】:

    • 其实我们可以通过在 Timer/timeit 中传递函数 calucation() 来找到执行时间,对吧?很好,但是像我在上面编辑的代码中提到的所有上述结果信息这样的统计数据呢?也就是说,如果我们将文件作为“python -m cProfile test.py”运行,我们将得到如上所示的整个输出(有多少函数调用等),但我不想用这个命令运行文件,而是当我将文件作为“python test.py”运行时,它应该显示所有结果如上,即我们需要在 test.py 文件中实现 cprofile 功能
    • 是的,你的问题。在我上面的示例中,结果包含所有 10000 个时间的列表。打印输出中的第一列是总调用次数,在我的示例中为 10000,因为这是传入的内容。第二列是总时间,这将是列表中值的总和,依此类推。
    猜你喜欢
    • 1970-01-01
    • 2012-05-14
    • 1970-01-01
    • 2011-01-07
    • 2023-02-15
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 2011-01-15
    相关资源
    最近更新 更多