如何找出我的代码中哪些部分在Python中效率低下 [英] How do I find out what parts of my code are inefficient in Python

查看:22
本文介绍了如何找出我的代码中哪些部分在Python中效率低下的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在前面的一个问题上,我问了一个关于多处理的问题,即使用多核来使程序运行得更快,有人告诉我:

通常情况下,与多处理相比,您可以通过更好的代码实现100倍以上的优化,而不是4倍的改进和额外的复杂性

然后他们建议我应该:

使用探查器了解速度较慢的原因,然后专注于优化。

所以我问了这个问题:How can you profile a script?

在这里我找到了cProfile,并将其实现到一些测试代码中,以查看它是如何工作的。

这是我的代码:

import cProfile

def foo():
    for i in range(10000):
        a = i**i
        if i % 1000 == 0:
            print(i)

cProfile.run('foo()')

但是,在运行它之后,我得到的结果如下:

0
1000
2000
3000
4000
5000
6000
7000
8000
9000
         1018 function calls in 20.773 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000   20.773   20.773 <string>:1(<module>)
      147    0.000    0.000    0.000    0.000 rpc.py:150(debug)
       21    0.000    0.000    0.050    0.002 rpc.py:213(remotecall)
       21    0.000    0.000    0.002    0.000 rpc.py:223(asynccall)
       21    0.000    0.000    0.048    0.002 rpc.py:243(asyncreturn)
       21    0.000    0.000    0.000    0.000 rpc.py:249(decoderesponse)
       21    0.000    0.000    0.048    0.002 rpc.py:287(getresponse)
       21    0.000    0.000    0.000    0.000 rpc.py:295(_proxify)
       21    0.001    0.000    0.048    0.002 rpc.py:303(_getresponse)
       21    0.000    0.000    0.000    0.000 rpc.py:325(newseq)
       21    0.000    0.000    0.002    0.000 rpc.py:329(putmessage)
       21    0.000    0.000    0.000    0.000 rpc.py:55(dumps)
       20    0.000    0.000    0.001    0.000 rpc.py:556(__getattr__)
        1    0.000    0.000    0.001    0.001 rpc.py:574(__getmethods)
       20    0.000    0.000    0.000    0.000 rpc.py:598(__init__)
       20    0.000    0.000    0.050    0.002 rpc.py:603(__call__)
       20    0.000    0.000    0.051    0.003 run.py:340(write)
        1   20.722   20.722   20.773   20.773 test.py:3(foo)
       42    0.000    0.000    0.000    0.000 threading.py:1226(current_thread)
       21    0.000    0.000    0.000    0.000 threading.py:215(__init__)
       21    0.000    0.000    0.047    0.002 threading.py:263(wait)
       21    0.000    0.000    0.000    0.000 threading.py:74(RLock)
       21    0.000    0.000    0.000    0.000 {built-in method _struct.pack}
       21    0.000    0.000    0.000    0.000 {built-in method _thread.allocate_lock}
       42    0.000    0.000    0.000    0.000 {built-in method _thread.get_ident}
        1    0.000    0.000   20.773   20.773 {built-in method builtins.exec}
       42    0.000    0.000    0.000    0.000 {built-in method builtins.isinstance}
       63    0.000    0.000    0.000    0.000 {built-in method builtins.len}
       10    0.000    0.000    0.051    0.005 {built-in method builtins.print}
       21    0.000    0.000    0.000    0.000 {built-in method select.select}
       21    0.000    0.000    0.000    0.000 {method '_acquire_restore' of '_thread.RLock' objects}
       21    0.000    0.000    0.000    0.000 {method '_is_owned' of '_thread.RLock' objects}
       21    0.000    0.000    0.000    0.000 {method '_release_save' of '_thread.RLock' objects}
       21    0.000    0.000    0.000    0.000 {method 'acquire' of '_thread.RLock' objects}
       42    0.047    0.001    0.047    0.001 {method 'acquire' of '_thread.lock' objects}
       21    0.000    0.000    0.000    0.000 {method 'append' of 'collections.deque' objects}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
       21    0.000    0.000    0.000    0.000 {method 'dump' of '_pickle.Pickler' objects}
       20    0.000    0.000    0.000    0.000 {method 'get' of 'dict' objects}
       21    0.000    0.000    0.000    0.000 {method 'getvalue' of '_io.BytesIO' objects}
       21    0.000    0.000    0.000    0.000 {method 'release' of '_thread.RLock' objects}
       21    0.001    0.000    0.001    0.000 {method 'send' of '_socket.socket' objects}

我希望它能向我显示代码的哪些部分花费的时间最长,例如,它显示a = i**i花费的计算时间最长,但从它告诉我的信息中,我所能收集到的信息是foo()函数花费的时间最长,然而,从数据中我不知道该函数内部花费的时间最长。

此外,当我将其实现到我的实际代码中时,它也会做同样的事情。一切都在函数中,它只告诉我哪些函数花费的时间最长,而不是函数中的哪些函数花费了这么长时间。

以下是我的主要问题:

  1. 我如何才能看到函数内部是什么导致代码花了这么长时间(我是否应该使用cProfile?)

  2. 在我知道什么是使用最多的CPU之后,开始优化我的代码的最佳方法是什么

注意:我的内存和磁盘等绝对正常,只有CPU超负荷(12%的CPU,因为它只在单核上运行)

推荐答案

如何了解函数内部是什么原因导致代码花了这么长时间(我是否应该使用cProfile?)

可以,您可以使用cProfile,但您提问的方式让我怀疑line_profiler(第三方模块,您需要安装它)是不是一个更好的工具。

当我想要分析函数时,我正在使用此包的IPython/Jupyter绑定:

%load_ext line_profiler

实际分析函数:

%lprun -f foo foo()
#             ^^^^^---- this call will be profiled
#         ^^^-----------function to profile

哪一项会产生此输出:

Timer unit: 5.58547e-07 s

Total time: 17.1189 s
File: <ipython-input-1-21b5a5f52f66>
Function: foo at line 1

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     1                                           def foo():
     2     10001        31906      3.2      0.1      for i in range(10000):
     3     10000     30534065   3053.4     99.6          a = i**i
     4     10000        75998      7.6      0.2          if i % 1000 == 0:
     5        10         6953    695.3      0.0              print(i)

这包括几件可能很有趣的事情。例如,99.6%的时间花费在i**i行中。

  1. 在我知道什么是使用最多的CPU之后,开始优化我的代码的最佳方法是什么

这要视情况而定。有时你需要使用不同的函数/数据结构/算法--有时你什么都做不了。但至少您知道瓶颈在哪里,并且可以估计瓶颈或其他地方的更改会产生多大影响。

这篇关于如何找出我的代码中哪些部分在Python中效率低下的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆