如何檢查Python指令碼的執行時間?


Python指令碼是一個可以儲存程式碼的檔案,用於執行特定任務或一組任務。此檔案以“.py”副檔名儲存。Python指令碼可以在任何文字編輯器中建立和編輯,並可以使用命令列提示符執行,或者可以作為包或模組匯入到整合開發環境(IDE)中。

每個Python指令碼都需要一些時間來執行檔案;可以使用以下方法計算它。

使用time模組

在Python中,我們有time模組,用於測量程式碼塊執行所需的時間。time模組的time()函式以秒為單位返回時間,然後計算開始時間和結束時間的差值,以獲得給定程式碼塊的執行時間。

示例

在這個例子中,我們將建立一個Python指令碼,並使用time模組的time()函式檢查其執行時間。

在程式碼中,我們將建立Python指令碼並將指令碼匯入到Python環境中,然後計算指令碼的執行時間。

import python_sample as ps
import time
start_time = time.time()
script = ps.python_script("Welcome to Tutorialspoint")
print(script)
end_time = time.time()
execution_time = start_time - end_time
print("Execution time:",execution_time)

輸出

給定Python指令碼的執行時間如下所示。

Welcome to Tutorialspoint
Execution time: -0.0009975433349609375

示例

讓我們看另一個例子,使用time模組的time()函式計算執行時間。

import python_sample as ps
import time
start_time = time.time()
statement = "Python is the most popular programming language"
print(statement)
end_time = time.time()
execution_time = start_time - end_time
print("Execution time:",execution_time)

輸出

給定Python程式碼片段的執行時間如下所示。

Python is the most popular programming language
Execution time: -0.0009970664978027344

使用timeit模組

timeit是另一個模組,它提供了一種更精確的方法來測量程式碼片段的執行時間,方法是多次執行它並查詢所有時間結果的平均值。

timeit模組提供timeit函式,該函式將指令碼作為輸入並計算執行時間;它以秒為單位返回結果。

示例

以下是計算Python指令碼執行時間的示例。

import python_sample as ps
import timeit
script = ps.python_script("Welcome to Tutorialspoint,Have a happy learning")
print(script)
execution_time = timeit.timeit(number = 50)
print("Execution time:",execution_time)

輸出

以下是使用timeit模組的timeit函式計算的Python指令碼執行時間的輸出。

Welcome to Tutorialspoint,Have a happy learning
Execution time: 1.100008375942707e-06

使用cProfile模組函式

cProfile是Python中可用的另一個模組,它查詢Python指令碼的執行時間。cProfile具有run()函式,該函式計算每個函式執行所花費的時間以及整個Python指令碼的執行時間。

示例

以下是使用cProfile模組run()函式計算執行時間的示例。

import cProfile
cProfile.run('python_sample')

輸出

       3 function calls in 0.000 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 <string>:1(<module>)
        1    0.000    0.000    0.000    0.000 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

示例

讓我們再看一個例子,使用cProfile模組run()函式計算Python指令碼的執行時間。

import cProfile
import sample
cProfile.run('sample')

輸出

以下是上述程式碼的輸出。

  3 function calls in 0.000 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000 :1()
        1    0.000    0.000    0.000    0.000 {built-in method builtins.exec}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

更新於:2023年8月9日

11K+ 次檢視

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.