簡體   English   中英

與 random.random() 相比,使用 random.uniform() 時 Visual Studio Code Python 調試器的運行速度明顯變慢

[英]Visual Studio Code Python debugger running significantly slower when using random.uniform() compared with random.random()

我的 Python 版本是 3.8.2,我使用 Visual Studio Code 1.43.1 來編寫代碼。 我正在使用蒙特卡羅方法估計 pi ​​的值。

事實證明,當我使用 random.random() 生成隨機數時,在發布模式下大約需要 1.4 秒,在調試器中大約需要 1.6 秒。 但是當我將 random.random() 切換到 random.uniform(0,1) 時,它在發布模式下大約需要 1.9 秒,在調試器中大約需要 6.5 秒。

我認為運行時間會增加是合理的,因為我每次生成一個數字時,統一函數都會進行額外的計算。 但是為什么在發布方式上只增加了一點點,而在調試器中使用的時間卻增加了近3倍呢? 這種現象背后的機制是什么? 還是我的調試器有問題?

我的代碼如下。 我已經刪除了調試器中的所有斷點。 由於我是 Python 的初學者,我沒有對設置做太多更改。

from random import random,uniform
from time import perf_counter
LEN=1000000
COUNT=0
start=perf_counter()
for i in range(LEN):
    x,y=uniform(0,1),uniform(0,1)  #switch between random() and uniform(0,1)
    dist=pow(x**2+y**2,0.5)
    if dist<=1.0:
        COUNT+=1
pi=4*COUNT/LEN
end=perf_counter()
print("pi={:10f}".format(pi))
print("time consumed:{:f}".format(end-start))

也許試試pypy和visual studio code python extension,它可以提高python調試器的性能。

暫無
暫無

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

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