簡體   English   中英

python時間結果與預期不符:time.time()-time.time()

[英]python time results not as expected: time.time() - time.time()

在處理time的python執行time ,我發現在單個語句中兩次調用time.time()時出現了奇怪的行為。 語句執行期間獲取time.time()處理延遲非常小。

例如time.time()-time.time()

如果在理想環境中立即執行,則結果將為0。

但是,在現實世界中,這會導致數量非常少,因為在處理器執行第一次time.time()計算和下次執行time時,假定存在延遲。 但是,當運行相同的執行並將其與以相同方式計算的變量進行比較時,結果將朝一個方向傾斜。

請參見下面的小代碼段。 對於非常大的數據集也是如此

import time

counts = 300000

def at_once():
  first = 0
  second = 0
  x = 0
  while x < counts:
      x += 1
      exec_first = time.time() - time.time()
      exec_second = time.time() - time.time()

      if exec_first > exec_second:
          first += 1
      else:
          second += 1


print('1sts: %s' % first)
print('2nds: %s' % second)

印刷品:

1sts: 39630
2nds: 260370

除非我的邏輯不正確,否則我期望結果非常接近50:50,但事實並非如此。 有誰能解釋造成這種現象的原因或指出導致結果偏向一個方向的代碼邏輯的潛在缺陷?

可能是exec_first == exec_second嗎? 在這種情況下,if-else會加1。

嘗試將if-else更改為以下內容:

if exec_first > exec_second:
    first += 1
elif exec_second > exec_first:
    second += 1
else:
    pass

您將所有關系分配給一個類別。 嘗試一下:

import time

counts = 300000
first = 0 
second = 0 
same = 0

for _ in range(counts):
    exec_first = time.time() - time.time()
    exec_second = time.time() - time.time()

    if exec_first == exec_second:
        same += 1
    elif exec_first > exec_second:
        first += 1 
    else:
        second += 1 

print('1sts: %s' % first)
print('same: %s' % same)
print('2nds: %s' % second)

輸出:

$ python3 so.py
1sts: 53099
same: 194616
2nds: 52285
$ python3 so.py
1sts: 57529
same: 186726
2nds: 55745

另外,對於您為什么認為函數調用可能花費0的時間,我感到困惑。 每次調用都至少需要訪問系統時鍾並將該值復制到某種臨時位置。 這在當前的任何計算機上都沒有多余的開銷。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM