My Python version is 3.8.2 and I use Visual Studio Code 1.43.1 to write my code. I'm estimating the value of pi using the Monte Carlo method. It turns out that when I use random.random() to generate random numbers, it takes me roughly 1.4s in release mode and 1.6s in the debugger. But when I switch the random.random() to random.uniform(0,1), it costs roughly 1.9s in the release mode and 6.5s in the debugger. I suppose it is reasonable that the running time will increase because each time I generate a number, the uniform function will do an additional calculation. But why is there only a slight increase in the release mode, while the time used in the debugger increases by nearly 3 times? What is the mechanism behind this phenomenon? Or is there something wrong with my debugger?
My code is listed below. I have deleted all breakpoints in the debugger. Since I'm a beginner for Python, I didn't do much change in the setting.
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))
Aucun commentaire:
Enregistrer un commentaire