Python 性能檢測分析方法 - 時間、空間衡量方法

来源:https://www.cnblogs.com/IT-QiuYe/archive/2022/11/23/16918946.html
-Advertisement-
Play Games

性能檢測分析方法 - 時間、空間衡量方法 Python 自帶模塊 import time 點擊查看代碼 # 僅僅是示範 time 模塊的用法,此段不能直接運行,運行請看測試項目源碼 import time def measure_runtime(func): time_start = time.ti ...


性能檢測分析方法 - 時間、空間衡量方法


Python 自帶模塊

import time

點擊查看代碼
# 僅僅是示範 time 模塊的用法,此段不能直接運行,運行請看測試項目源碼
import time

def measure_runtime(func):
    time_start = time.time()
    func()
    time_end = time.time()
    print(time_end - time_start)

measure_runtime(lambda :out_Sorted_list("插入排序","InsertSort"))

import timeit

點擊查看代碼
# 僅僅是示範 timeit 模塊的用法,此段不能直接運行,運行請看測試項目源碼
# 運行五次插入排序函數得到使用時間
temp = timeit.timeit(lambda : out_Sorted_list("插入排序","InsertSort"),number=5)
print(temp)

第三方模塊

pip install memory_profiler

♠ 能夠監視進程、瞭解記憶體使用等情況

點擊查看代碼
from memory_profiler import profile

@profile
def get_Unordered_list():
    A = [2, 3, 1, 4, 2, 6]
    print("排序前列表:",A)
    return A

get_Unordered_list()

運行後


點擊查看運行結果
Line #    Mem usage    Increment  Occurrences   Line Contents
=============================================================
    39     34.4 MiB     34.4 MiB           1   @profile
    40                                         def get_Unordered_list():
    41     34.4 MiB      0.0 MiB           1       A = [2, 3, 1, 4, 2, 6]
    42     34.4 MiB      0.0 MiB           1       print("排序前列表:",A)
    43     34.4 MiB      0.0 MiB           1       return A

pip install line_profiler

♣ 代碼行運行時間檢測

點擊查看代碼
from line_profiler import LineProfiler

lp = LineProfiler()
lp_wrap = lp(get_Unordered_list)
lp_wrap()

lp.print_stats()

運行後


點擊查看代碼
排序前列表: [2, 3, 1, 4, 2, 6]
Timer unit: 1e-07 s
Total time: 2.43e-05 s
File: E:/Python_Projects/Test_Env/Test_Project/演算法導論_第三版/Chapter_2_演算法基礎.py
Function: get_Unordered_list at line 40
Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    40                                           def get_Unordered_list():
    41         1          6.0      6.0      2.5      A = [2, 3, 1, 4, 2, 6]
    42         1        217.0    217.0     89.3      print("排序前列表:",A)
    43         1         20.0     20.0      8.2      return A

pip install heartrate

♥ 可視化檢測工具

點擊查看代碼
import heartrate

heartrate.trace(browser=True)

def InsertSort(noSortedlist):
    """
    插入排序:對於少量元素的排序\n
    輸入:輸入一個未排序數組/列表\n
    輸出:輸出一個從小到大排序好的數組/列表\n
    For example: 手中撲克牌排序
    """
    for j in range(1,len(noSortedlist)):
        key = noSortedlist[j]
        i = j-1
        while i >= 0 and noSortedlist[i] > key:
            noSortedlist[i+1] = noSortedlist[i]
            i = i -1
        noSortedlist[i+1] = key
    return noSortedlist

import heartrate
heartrate.trace(browser=True)

A = [2, 3, 1, 4, 2, 6]
print(InsertSort(A))

運行後


image


測試項目源碼

點擊查看項目源碼
""" 演算法基礎 """
# In[]
""" 2.1 插入排序 """
from memory_profiler import profile

# 輸入是一個序列 A =[2,3,1,4,2,6]
def InsertSort(noSortedlist):
    """
    插入排序:對於少量元素的排序\n
    輸入:輸入一個未排序數組/列表\n
    輸出:輸出一個從小到大排序好的數組/列表\n
    For example: 手中撲克牌排序
    """
    for j in range(1,len(noSortedlist)):
        key = noSortedlist[j]
        i = j-1
        while i >= 0 and noSortedlist[i] > key:
            noSortedlist[i+1] = noSortedlist[i]
            i = i -1
        noSortedlist[i+1] = key
    return noSortedlist

@profile
def get_Unordered_list():
    A = [2, 3, 1, 4, 2, 6]
    print("排序前列表:",A)
    return A

def out_Sorted_list(name,methodName):
    method = eval(str(methodName))
    sorted_list = method(get_Unordered_list())
    print(f"使用{name}排序後列表:",sorted_list)

def measure_runtime(func):
    time_start = time.time()
    func()
    time_end = time.time()
    print(time_end - time_start)

if __name__ == '__main__':
    import timeit
    import time
    # 衡量插入排序
    print(timeit.timeit(lambda : out_Sorted_list("插入排序","InsertSort"),number=5))
    measure_runtime(lambda :out_Sorted_list("插入排序","InsertSort"))


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 由於博主有很多個python環境,如msys64的python,anaconda3的python和官網下載的python, 當我在vscode運行python,需要安裝對應的包時,用pip安裝,如下 安裝成功了,但是還是沒有找到 原因非常簡單,就是我vscode使用的python環境不是上面那個py ...
  • new ,delete 運算符 int *p =new int; delete p; 看一下彙編代碼 可以看到new 和delete 運算符其實也是 operator運算符重載函數的調用 malloc和new malloc 按位元組開闢記憶體 new在開闢記憶體的時候需要指定類型 new int[10] ...
  • 一.小結 1.迴圈語句有三類:while迴圈,do-while迴圈和for迴圈 2.迴圈中需要重覆執行的語句所構成的整體稱為迴圈體 3.迴圈體執行一次稱為迴圈的一次迭代 4.無限迴圈是指迴圈語句被無限次執行 5.在設計迴圈時,既需要考慮迴圈控制構體,還需要考慮迴圈體 6.while迴圈首先檢查迴圈繼 ...
  • WEB開發會話技術04 14.Session生命周期 14.1生命周期說明 public void setMaxInactiveInterval(int interval):設置session的超時時間(以秒為單位),超過指定的時長,session就會被銷毀。 值為正數的時候,設置session的超 ...
  • 遞歸與Stream流轉換 今天寫一個很久以前一直不太會的,今天花了大量的時間進行研究處理,現將代碼解析於此 list轉為類中一個屬性為key,類實例為value的Map Map<String, List<OrgTreeVo>> orgMap = orgList.stream().filter(h - ...
  • 目錄 一.OpenGL 圖像褐色 1.原始圖片 2.效果演示 二.OpenGL 圖像褐色源碼下載 三.猜你喜歡 零基礎 OpenGL ES 學習路線推薦 : OpenGL ES 學習目錄 >> OpenGL ES 基礎 零基礎 OpenGL ES 學習路線推薦 : OpenGL ES 學習目錄 >> ...
  • 上篇文章談到BlockingQueue的使用場景,並重點分析了ArrayBlockingQueue的實現原理,瞭解到ArrayBlockingQueue底層是基於數組實現的阻塞隊列。 但是BlockingQueue的實現類中,有一種阻塞隊列比較特殊,就是SynchronousQueue(同步移交隊... ...
  • 1、const修飾變數 被const修飾過的變數相當於常量,它的值不能被賦值改變,在整個作用域內保持固定。所以說它定義的是只讀變數,在定義的時候需要給它賦初值。 1 const int a = 1; 2 a = 2; /*錯誤,常量的值不能改變*/ 3 const int a; /*錯誤,常量定義時 ...
一周排行
    -Advertisement-
    Play Games
  • 1. 說明 /* Performs operations on System.String instances that contain file or directory path information. These operations are performed in a cross-pla ...
  • 視頻地址:【WebApi+Vue3從0到1搭建《許可權管理系統》系列視頻:搭建JWT系統鑒權-嗶哩嗶哩】 https://b23.tv/R6cOcDO qq群:801913255 一、在appsettings.json中設置鑒權屬性 /*jwt鑒權*/ "JwtSetting": { "Issuer" ...
  • 引言 集成測試可在包含應用支持基礎結構(如資料庫、文件系統和網路)的級別上確保應用組件功能正常。 ASP.NET Core 通過將單元測試框架與測試 Web 主機和記憶體中測試伺服器結合使用來支持集成測試。 簡介 集成測試與單元測試相比,能夠在更廣泛的級別上評估應用的組件,確認多個組件一起工作以生成預 ...
  • 在.NET Emit編程中,我們探討了運算操作指令的重要性和應用。這些指令包括各種數學運算、位操作和比較操作,能夠在動態生成的代碼中實現對數據的處理和操作。通過這些指令,開發人員可以靈活地進行算術運算、邏輯運算和比較操作,從而實現各種複雜的演算法和邏輯......本篇之後,將進入第七部分:實戰項目 ...
  • 前言 多表頭表格是一個常見的業務需求,然而WPF中卻沒有預設實現這個功能,得益於WPF強大的控制項模板設計,我們可以通過修改控制項模板的方式自己實現它。 一、需求分析 下圖為一個典型的統計表格,統計1-12月的數據。 此時我們有一個需求,需要將月份按季度劃分,以便能夠直觀地看到季度統計數據,以下為該需求 ...
  • 如何將 ASP.NET Core MVC 項目的視圖分離到另一個項目 在當下這個年代 SPA 已是主流,人們早已忘記了 MVC 以及 Razor 的故事。但是在某些場景下 SSR 還是有意想不到效果。比如某些靜態頁面,比如追求首屏載入速度的時候。最近在項目中回歸傳統效果還是不錯。 有的時候我們希望將 ...
  • System.AggregateException: 發生一個或多個錯誤。 > Microsoft.WebTools.Shared.Exceptions.WebToolsException: 生成失敗。檢查輸出視窗瞭解更多詳細信息。 內部異常堆棧跟蹤的結尾 > (內部異常 #0) Microsoft ...
  • 引言 在上一章節我們實戰了在Asp.Net Core中的項目實戰,這一章節講解一下如何測試Asp.Net Core的中間件。 TestServer 還記得我們在集成測試中提供的TestServer嗎? TestServer 是由 Microsoft.AspNetCore.TestHost 包提供的。 ...
  • 在發現結果為真的WHEN子句時,CASE表達式的真假值判斷會終止,剩餘的WHEN子句會被忽略: CASE WHEN col_1 IN ('a', 'b') THEN '第一' WHEN col_1 IN ('a') THEN '第二' ELSE '其他' END 註意: 統一各分支返回的數據類型. ...
  • 在C#編程世界中,語法的精妙之處往往體現在那些看似微小卻極具影響力的符號與結構之中。其中,“_ =” 這一組合突然出現還真不知道什麼意思。本文將深入剖析“_ =” 的含義、工作原理及其在實際編程中的廣泛應用,揭示其作為C#語法奇兵的重要角色。 一、下劃線 _:神秘的棄元符號 下劃線 _ 在C#中並非 ...