Flask 效能分析與SQL慢查詢發現機制

2021-10-03 15:42:43 字數 2325 閱讀 3882

from werkzeug.middleware.profiler import profilermiddleware
輸出的形式如下

path: '/***/yyy/1'

45309 function calls (44223 primitive calls) in 0.085 seconds

ordered by: internal time, call count

ncalls tottime percall cumtime percall filename:lineno(function)

593 0.017 0.000 0.017 0.000

18 0.016 0.001 0.016 0.001

675 0.007 0.000 0.007 0.000

如果ncall有兩個數字(例如3/1),則表示函式遞迴。第二個值是原始呼叫次數,第乙個是呼叫的總次數。請注意,當函式不遞迴時,這兩個值是相同的,並且只列印單個數字。

class

stream:寫入統計資訊到指定stream中,指定none關閉寫入

sort_by:tuple型別。指定如何對統計資訊進行排序。 詳見pstats.stats.sort_stats()

restriction:tuple型別。限制輸出結果。詳見pstats.stats.print_stats()

profile_dir:指定乙個目錄。儲存效能度量資料檔案(.prof)到此目錄。

filename_format:度量資料檔案命名格式。可以指定乙個字串,也可以指定乙個可呼叫型別返回。

安裝依賴

pip install gprof2dot    # 將.prof檔案儲存的資料轉換為dot語言

brew install graphviz # 根據dot語言的描述繪圖

生成呼叫樹

python -m gprof2dot -f pstat your_prof_file.prof | dot -tsvg -o profile.svg
生成呼叫樹樣式的含義:

+------------------------------+

| function name |

| total time % ( self time % ) |

| total calls |

+------------------------------+

total time %

calls

parent --------------------> children

使用flask_sqlalchemy.get_debug_queries(),其記錄了在乙個請求中的所有sql的相關資訊。所以我們可以通過其來達成如發生慢查詢郵件通知等能力。

from flask_sqlalchemy import get_debug_queries

# sql效能測試

'sqlalchemy_record_queries']=

true

slow_sql_benchmark_in_ms =

0def

print_slow_sql

(response)

:assert slow_sql_benchmark_in_ms >=

0, \

"slow_sql_benchmark_in_ms 必須大於等於0"

for query in get_debug_queries():

if query.duration *

1000

> slow_sql_benchmark_in_ms:

f"slow query: duration: ms; "

f"; parameters: ; "

f"context: "

)return response

報錯:attributeerror: module 『profile』 has no attribute 『run』

解決方案:檢視是否有名稱為profile的包或檔案,刪除它就可以解決了。

werkzeug效能度量官方文件

python3.7 profilers

gprof2dot效能分析圖繪製包

圖形化工具graphviz

效能測試mysql慢SQL定位以及分析方法

效能測試過程定性的效能測試經常需要對mysql進行監控以及sql優化,其中慢sql和索引一直都是 一 通過mysql自帶的日誌查詢 1 最常見的是直接讀取或者使用spotlight monyog等第三方工具展示slow log。首先在server端配置開啟slow log以及時間閾值。修改 etc ...

專案慢查詢效能分析

mysql中慢查詢 show variables like slow query log 修改慢查詢狀態 set global slow query log on 沒有使用索引的查詢是否開啟 show variables like log queries not using indexes 慢查詢時...

分析sql效能

很多時候,我們不太清楚自己寫的sql語句好還是不好,往往資料量一大,程式執行變慢。其實在sql plus裡可以很清晰的分析出sql語句的執行計畫,它可以提醒我們來建立索引或改變sql語句的寫法。先在sys使用者下執行 oracle home rdbms sqlplus admin plustrce....