# python matplotlib - 你如何描述腳本？

## performance profiling time-complexity (19)

statprofstatprof ，所以可以通過指定git存儲庫來使用`pip`進行安裝：

``````pip install git+git://github.com/bos/[email protected]
``````

``````import statprof

with statprof.profile():
my_questionable_function()
``````

# 無命令行分析

``````def count():
from math import sqrt
for x in range(10**5):
sqrt(x)

if __name__ == '__main__':
import cProfile, pstats
cProfile.run("count()", "{}.profile".format(__file__))
s = pstats.Stats("{}.profile".format(__file__))
s.strip_dirs()
s.sort_stats("time").print_stats(10)
``````

``````python -m cProfile -s time mine.py <args>
``````

``````python -m cProfile -o output.file mine.py <args>
``````

PS>如果您使用的是Ubuntu，請確保安裝python-profile

``````sudo apt-get install python-profiler
``````

PyCallGraph：創建通話圖形圖像的工具

`````` sudo pip install pycallgraph
``````

`````` pycallgraph mine.py args
``````

`````` gimp pycallgraph.png
``````

``````pycallgraph -f svg -o pycallgraph.svg mine.py <args>
``````

PS>確保安裝graphviz（提供點程序）：

``````sudo pip install graphviz
``````

``````sudo pip install gprof2dot
python -m cProfile -o profile.pstats mine.py
gprof2dot -f pstats profile.pstats | dot -Tsvg -o mine.svg
``````

Python包含一個名為cProfile的分析器。 它不僅提供了總運行時間，而且還分別計算每個函數的時間，並告訴您每個函數被調用的次數，從而可以輕鬆確定應該在哪裡進行優化。

``````import cProfile
cProfile.run('foo()')
``````

``````python -m cProfile myscript.py
``````

``````python -m cProfile %1
``````

``````profile euler048.py
``````

``````1007 function calls in 0.061 CPU seconds

Ordered by: standard name
ncalls  tottime  percall  cumtime  percall filename:lineno(function)
1    0.000    0.000    0.061    0.061 <string>:1(<module>)
1000    0.051    0.000    0.051    0.000 euler048.py:2(<lambda>)
1    0.005    0.005    0.061    0.061 euler048.py:2(<module>)
1    0.000    0.000    0.061    0.061 {execfile}
1    0.002    0.002    0.053    0.053 {map}
1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler objects}
1    0.000    0.000    0.000    0.000 {range}
1    0.003    0.003    0.003    0.003 {sum}
``````

``````1. pip install snakeviz

2. python -m cProfile -o temp.dat <PROGRAM>.py

3. snakeviz temp.dat
``````

``````python -m cProfile -o script.profile script.py
pyprof2calltree -i script.profile -o script.calltree
kcachegrind script.calltree
``````

``````apt-get install kcachegrind
pip install pyprof2calltree
``````

• 將分析器附加到正在運行的（CPython）程序
• 按需分析與Yappi整合
• 在不同機器上的配置文件
• 多進程支持（多處理，Django ...）
• 實時採樣/ CPU視圖（帶時間範圍選擇）
• 通過cProfile / profile集成進行確定性分析
• 分析現有的PStats結果
• 打開DOT文件
• 程序化API訪問
• 按方法或行分組樣本
• PyDev集成
• PyCharm集成

# pprofile

`line_profiler` （這裡已經介紹過）也啟發了`pprofile` ，它被描述為：

# vprof

@ Maxy對這個答案的評論幫了我很大的印象，我認為它應該有自己的答案：我已經有了cProfile生成的.pstats文件，我不想用pycallgraph重新運行，所以我使用了gprof2dot ， svgs：

``````\$ sudo apt-get install graphviz
\$ git clone https://github.com/jrfonseca/gprof2dot
\$ ln -s "\$PWD"/gprof2dot/gprof2dot.py ~/bin
\$ cd \$PROJECT_DIR
\$ gprof2dot.py -f pstats profile.pstats | dot -Tsvg -o callgraph.svg
``````

``````python lsprofcalltree.py -o callgrind.1 test.py
``````

``````@staticmethod
def startProfiler():
yappi.start()

@staticmethod
def stopProfiler():
yappi.stop()

@staticmethod
def printProfiler():
stats = yappi.get_stats(yappi.SORTTYPE_TTOT, yappi.SORTORDER_DESC, 20)
statPrint = '\n'
namesArr = [len(str(stat[0])) for stat in stats.func_stats]
log.debug("namesArr %s", str(namesArr))
maxNameLen = max(namesArr)
log.debug("maxNameLen: %s", maxNameLen)

for stat in stats.func_stats:
nameAppendSpaces = [' ' for i in range(maxNameLen - len(stat[0]))]
log.debug('nameAppendSpaces: %s', nameAppendSpaces)
blankSpace = ''
for space in nameAppendSpaces:
blankSpace += space

statPrint = statPrint + str(stat[0]) + blankSpace + " " + str(stat[1]).ljust(8) + "\t" + str(
round(stat[2], 2)).ljust(8 - len(str(stat[2]))) + "\t" + str(round(stat[3], 2)) + "\n"

log.log(1000, "\nname" + ''.ljust(maxNameLen - 4) + " ncall \tttot \ttsub")
log.log(1000, statPrint)
``````

``````2014-02-19 16:32:24,128-|SVR-MAIN  |-(Thread-3   )-Level 1000:
name                                                                                                                                      ncall     ttot    tsub
C:\Python27\lib\sched.py.run:80                                                                                                           22        0.11    0.05
C:\Python27\lib\BaseHTTPServer.py.date_time_string:464                                                                                    1         0.0     0.0
c:\users\zasiec~1\appdata\local\temp\easy_install-hwcsr1\psutil-1.1.2-py2.7-win32.egg.tmp\psutil\_psmswindows.py._get_raw_meminfo:243     4         0.0     0.0
C:\Python27\lib\SimpleXMLRPCServer.py.decode_request_content:537                                                                          1         0.0     0.0
c:\users\zasiec~1\appdata\local\temp\easy_install-hwcsr1\psutil-1.1.2-py2.7-win32.egg.tmp\psutil\_psmswindows.py.get_system_cpu_times:148 4         0.0     0.0
<string>.__new__:8                                                                                                                        220       0.0     0.0
C:\Python27\lib\socket.py.close:276                                                                                                       4         0.0     0.0
<string>.__new__:8                                                                                                                        4         0.0     0.0
C:\Python27\lib\BaseHTTPServer.py.handle_one_request:301                                                                                  1         0.0     0.0
C:\Python27\lib\xmlrpclib.py.end:816                                                                                                      3         0.0     0.0
C:\Python27\lib\SimpleXMLRPCServer.py.do_POST:467                                                                                         1         0.0     0.0
C:\Python27\lib\SimpleXMLRPCServer.py.is_rpc_path_valid:460                                                                               1         0.0     0.0
C:\Python27\lib\SocketServer.py.close_request:475                                                                                         1         0.0     0.0
c:\users\zasiec~1\appdata\local\temp\easy_install-hwcsr1\psutil-1.1.2-py2.7-win32.egg.tmp\psutil\__init__.py.cpu_times:1066               4         0.0     0.0
``````

Inspect Shell不是一個pdb樣式的調試器。

``````class ProfiledThread(threading.Thread):
def run(self):
profiler = cProfile.Profile()
try:
finally:
profiler.dump_stats('myprofile-%d.profile' % (self.ident,))
``````

## 使用Intel x86仿真器加速器

HAXM與英特爾設備配合使用，因此創建了一個帶有英特爾CPU的新仿真器。