Python 性能分析

2019-01-05 21:03:05 +08:00
 fanhaipeng0403
import time


def countdown(n):
    while n > 0:
        n -= 1

第一种:

class Timer:
    def __init__(self, func=time.perf_counter):
        self.elapsed = 0.0
        self._func = func
        self._start = None

    def start(self):
        if self._start is not None:
            raise RuntimeError('Already started')
        self._start = self._func()

    def stop(self):
        if self._start is None:
            raise RuntimeError('Not started')
        end = self._func()
        self.elapsed += end - self._start
        self._start = None

    def reset(self):
        self.elapsed = 0.0

    @property
    def running(self):
        return self._start is not None

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, *args):
        self.stop()



In [68]: with Timer() as t2:
    ...:     countdown(1000000)
    ...: print(t2.elapsed)
    ...:
0.06051115319132805




第二种:

In [27]: def profile(func):
    ...:     def wrapper( *args, **kwargs):
    ...:         start = time.time()
    ...:         func(*args, **kwargs)
    ...:         end = time.time()
    ...:         print(end - start)
    ...:     return wrapper
    ...:
 In [28]: @profile
    ...: def countdown(n):
    ...:     while n > 0:
    ...:         n -= 1
    ...:
  
In [80]: countdown(1000000)
0.0597081184387207     
        
        
        
第三种

ipython

In [67]: %timeit countdown(1000000)
10 loops, best of 3: 59.3 ms per loop
    
    
第四种

>>> import cProfile
>>> def countdown(n):
...     while n > 0:
...         n -= 1
...
>>> cProfile.run('countdown(1000000)')
         4 function calls in 0.068 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.068    0.068    0.068    0.068 <stdin>:1(countdown)
        1    0.000    0.000    0.068    0.068 <string>:1(<module>)
        1    0.000    0.000    0.068    0.068 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

使用可视化:

>>> import cProfile
>>> def countdown(n):
...     while n > 0:
...         n -= 1
...
>>> cProfile.run('countdown(1000000)',"result")
         4 function calls in 0.068 seconds
    
snakeviz result
1662 次点击
所在节点    Python
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/524241

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX