python中perf_counter_Python time.perf_counter()用法及代码示例
由于時間模塊提供了各種與時間有關的功能。因此,有必要導入時間模塊,否則會出錯,因為時間模塊中存在perf_counter()的定義。
perf_counter()函數始終以秒為單位返回時間的浮點值。返回性能計數器的值(以分數秒為單位),即具有最高可用分辨率的時鐘以測量短時間。它確實包括睡眠期間經過的時間,并且為system-wide。返回值的參考點是不確定的,因此僅連續調用結果之間的差有效。在這之間,我們可以使用time.sleep()和類似的功能。
代碼1:了解perf_counter的用法。
# Python program to show time by perf_counter()
from time import perf_counter
# integer input from user, 2 input in single line
n, m = map(int, input().split())
# Start the stopwatch / counter
t1_start = perf_counter()
for i in range(n):
t = int(input()) # user gave input n times
if t % m == 0:
print(t)
# Stop the stopwatch / counter
t1_stop = perf_counter()
print("Elapsed time:", t1_stop, t1_start)
print("Elapsed time during the whole program in seconds:",
t1_stop-t1_start)
輸出:
pref_counter_ns():
它始終以納秒為單位給出時間的整數值。與perf_counter()相似,但返回時間以納秒為單位。
代碼2:perf_counter_ns的用法以及如何實現。
# Python program to show time by
# perf_counter_ns()
from time import perf_counter_ns
# integer input from user, 2 input in single line
n, m = map(int, input().split())
# Start the stopwatch / counter
t1_start = perf_counter_ns()
for i in range(n):
t = int(input()) # user gave input n times
if t % m == 0:
print(t)
# Stop the stopwatch / counter
t1_stop = perf_counter_ns()
print("Elapsed time:", t1_stop, 'ns', t1_start, 'ns')
print("Elapsed time during the whole program in ns after n, m inputs:",
t1_stop-t1_start, 'ns')
輸出:
比較程序的兩個輸出,因為perf_counter()以秒為單位返回,pers_counter_ns()以納秒為單位返回。
perf_counter()的優點:
1. perf_counter()會比time.clock()功能。
2.從Python3.8開始,將刪除clock()函數,并使用perf_counter。
3.我們可以計算浮點數和整數時間值(以秒和納秒為單位)。
總結
以上是生活随笔為你收集整理的python中perf_counter_Python time.perf_counter()用法及代码示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: html控制台随机数取整,获取随机数、浮
- 下一篇: 湄洲岛风光-鹅尾神石园