欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python實(shí)現(xiàn)微秒級(jí)等待問題(windows)

 更新時(shí)間:2024年06月24日 09:08:04   作者:霸蠻哥  
這篇文章主要介紹了python實(shí)現(xiàn)微秒級(jí)等待問題(windows),具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

python實(shí)現(xiàn)微秒級(jí)等待

windows限制

python 的 time.sleep()方法,在windows操作系統(tǒng)下,最低只能實(shí)現(xiàn)到0.001秒,即最少等待1毫秒。

時(shí)間單位

  • 秒(second),時(shí)間單位 : s, 
  • 毫秒(millisecond),時(shí)間單位:ms 
  • 微秒(microsecond),時(shí)間單位:μs

時(shí)間換算:

  • 1s【秒】 = 1000ms【毫秒】
  • 1ms【毫秒】 = 1000μs【微秒】
  • 1μs【微秒】 = 1000ns【納秒】
  • 1ns 【納秒】= 1000ps【皮秒】

如何實(shí)現(xiàn)微秒μs級(jí)等待?

可使用time.perf_counter()方法來實(shí)現(xiàn)。

代碼如下:

import time


def microsecond_sleep(sleep_time):
    """微秒等待

    :param sleep_time: int, 微秒
    :return:
    """

    end_time = time.perf_counter() + (sleep_time - 0.8) / 1e6  # 0.8是時(shí)間補(bǔ)償,需要根據(jù)自己PC的性能去實(shí)測(cè)
    while time.perf_counter() < end_time:
        pass


start = time.perf_counter()
microsecond_sleep(10)  # 等待10微秒
end = time.perf_counter()
print(start)
print(end)
print("等待時(shí)間:", (end-start) * 1e6, "微秒")

運(yùn)行結(jié)果如下:

1040204.7426661
1040204.742676
等待時(shí)間: 9.899958968162537 微秒

多次測(cè)試,實(shí)際消耗時(shí)間在9.89-10.30微秒之間。

python編程,毫秒級(jí)延時(shí)的一種實(shí)現(xiàn)

linux適用

import time    # 導(dǎo)入time模塊
 
def delayMicrosecond(t):    # 微秒級(jí)延時(shí)函數(shù)
    start,end=0,0           # 聲明變量
    start=time.time()       # 記錄開始時(shí)間
    t=(t-3)/1000000     # 將輸入t的單位轉(zhuǎn)換為秒,-3是時(shí)間補(bǔ)償
    while end-start<t:  # 循環(huán)至?xí)r間差值大于或等于設(shè)定值時(shí)
        end=time.time()     # 記錄結(jié)束時(shí)間

a=time.time()   # 記錄延時(shí)函數(shù)開始執(zhí)行時(shí)的時(shí)間
delayMicrosecond(10)	#延時(shí) 35 微秒
b=time.time()   # 記錄延時(shí)函數(shù)結(jié)束時(shí)的時(shí)間
print((b))
print((a))

print((b-a)*1000000)

windows適用

import time    # 導(dǎo)入time模塊

def procedure():
    time.sleep(2.5)

# measure process time
t0 = time.process_time()
procedure()
print (time.process_time() - t0, "seconds process time")

# measure wall time
t0 = time.time()
procedure()
print (time.time() - t0, "seconds wall time")

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論