Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中查找代码的统计信息和执行时间_Python_Statistics_Execution Time - Fatal编程技术网

如何在python中查找代码的统计信息和执行时间

如何在python中查找代码的统计信息和执行时间,python,statistics,execution-time,Python,Statistics,Execution Time,我正在研究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_

我正在研究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
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}
因此,从上面的代码中,我可以找到代码的执行时间,但是如何在python中找到代码的统计信息呢

最后,我的意图如下

  • 如何在python中查找代码的统计信息
  • 如何在python中找到整个代码的执行时间
  • 代码的统计数据实际上意味着什么
  • 编辑的代码:

    0.2561519145965576
    
    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
    
    结果:

    0.2561519145965576
    
    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}
    
    sh-4.2$python-mcprofile test.py
    在0.001秒内进行4次函数调用
    订购人:标准名称
    ncalls tottime percall cumtime percall文件名:lineno(函数)
    1 0.001 0.001 0.001 0.001试验。py:1()
    1 0.000 0.000 0.000 0.000 timeit.py:105(定时器)
    1 0.001 0.001 0.001 0.001 timeit.py:53()
    1 0.000 0.000 0.000 0.000{方法'disable'的''lsprof.Profiler'对象}
    
    所以当我运行上面的代码时,我需要这样的东西,我尝试的是在文件
    test.py
    中编写打印统计信息的功能,而不是从终端运行命令
    python-mcprofile test.py


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

    您要问的似乎是如何为timeit模块创建编程接口。这是有案可查的。您将需要一个样本集来计算统计信息,如min、max、average等,这意味着要通过Timeit模块中包含的Timeit类的repeat方法多次运行calculate

    例如:

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

    我想你是在问如何在代码中使用
    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()
    


    您可以根据需要更改
    print\u stats
    ,以显示所需的输出。

    您所说的“代码统计信息”是什么意思?您可能需要分析(这是进一步研究的关键字)。另请看和。@chris:这就是我的疑问。事实上,我不知道为什么会投否决票,我对此表示怀疑,并与SOI接洽。我编辑了我的代码。上面有人可以看一下……实际上,我们可以通过在Timer/timeit right中传递函数calucation()来找到执行时间?。好的,但是统计数据呢,比如我需要上面编辑代码中提到的所有结果信息。也就是说,如果我们以“python-mcprofile test.py”的形式运行该文件,我们将获得如上所述的整个输出(有多少个函数调用等),但我不想用这个命令运行该文件,而是当我以“python test.py”的形式运行该文件时,它应该显示如上所述的所有结果,也就是说,我们需要在test.py文件中实现cprofile功能。在我上面的示例中,结果包含所有10000次计时的列表。打印输出中的第一列是调用总数,在我的示例中是10000,因为这是传入的。第二列是total time,它是列表中的值之和,依此类推。