使用profile类优化Python代码

2024-09-30 01:30:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码在我做了一些最后的修改后变得非常慢。一个搜索任务需要102秒而不是2-3秒。

我尝试使用profile类来找到限制函数,下面是输出:

>>> import WebParser
>>>
>>> w = WebParser.LinksGrabber
>>>
>>> import cProfile
>>> cProfile.run("w.search('nicki minaj', 15)")
         50326 function calls in 102.745 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000  102.745  102.745 <string>:1(<module>)
        6    0.000    0.000    0.000    0.000 Config.py:110(__getattr__)
        1    0.000    0.000  102.745  102.745 LinksGrabber.py:427(search)
        5    0.000    0.000    0.002    0.000 Queue.py:107(put)
      911    0.040    0.000  102.726    0.113 Queue.py:150(get)
       ..................................
      }
     6836    0.022    0.000    0.022    0.000 {min}
      917    0.009    0.000    0.009    0.000 {thread.allocate_lock}
        3    0.000    0.000    0.000    0.000 {thread.get_ident}
        3    0.000    0.000    0.000    0.000 {thread.start_new_thread}
    6835  100.458    0.015  100.458    0.015 {time.sleep}
    11346    0.035    0.000    0.035    0.000 {time.time}

它显示一个time.sleep代码正在等待100.458s,但是我在我的WebParser.LinksGrabber类中找不到该代码段。

我如何使用profile来获得关于慢代码段的更多信息?


Tags: 代码pyimportsearchgettimequeuefunction
1条回答
网友
1楼 · 发布于 2024-09-30 01:30:42

我有一段样板代码添加到需要评测的程序中,我可以通过将PROFILE变量改为TrueFalse来轻松启用或禁用它。。。在

#!/usr/bin/env python

# Should we profile the code?
PROFILE = True

# What proportion of the profile data should we keep?
PROFILE_LIMIT = 0.5         # 50%

# Where to store the raw profile data
PROFILE_DAT = 'profile.dat'

# Where to store the formatted profile data
PROFILE_TXT = 'profile.txt'


# Main code starts here
import time

def do_something():
    for i in range(5):
        time.sleep(0.1)

def do_something_else():
    for i in range(10):
        time.sleep(0.1)

def main():
    do_something()
    do_something_else()


if __name__ == '__main__':

    if PROFILE:
        import os, cProfile, pstats
        cProfile.runctx('main()', globals(), locals(), PROFILE_DAT)
        f = open(PROFILE_TXT, 'wb')
        for sort_key in 'time', 'cumulative':
            stats = pstats.Stats(PROFILE_DAT, stream=f)
            stats.sort_stats(sort_key)
            stats.print_stats(PROFILE_LIMIT)
            stats.strip_dirs()
            stats.sort_stats(sort_key)
            if sort_key == 'time':
                stats.print_callers(PROFILE_LIMIT)
            else:
                stats.print_callees(PROFILE_LIMIT)
        f.close()
        os.unlink(PROFILE_DAT)

    else:
        main()

…它创建一个文本文件profile.txt,其中包含。。。在

  1. 最慢的函数(内部)以及调用它们的位置
  2. 最慢的函数(累积)以及它们所称的

…看起来像这样。。。在

^{pr2}$

…这通常足以跟踪代码需要改进的地方。在

相关问题 更多 >

    热门问题