Python 如何提高程序中嵌套循环的速度?
我在玩老虎机模拟器 程序的核心是一个嵌套循环,如下所示:Python 如何提高程序中嵌套循环的速度?,python,pandas,performance,optimization,multiprocessing,Python,Pandas,Performance,Optimization,Multiprocessing,我在玩老虎机模拟器 程序的核心是一个嵌套循环,如下所示: import pandas for universe in range(10000): for spins in range(50000): win = paytable.Multiplier.sample(weights=paytable.Probability) result.append(win) 宇宙是应该模拟下注过程的次数 自旋是每个宇宙中的自旋数量 该程序从熊猫数据帧中进行加权选择,
import pandas
for universe in range(10000):
for spins in range(50000):
win = paytable.Multiplier.sample(weights=paytable.Probability)
result.append(win)
宇宙是应该模拟下注过程的次数
自旋是每个宇宙中的自旋数量
该程序从熊猫数据帧中进行加权选择,以确定旋转是否获胜以及获胜多少
问题是我需要执行所有这些操作以获得足够大的样本量,而这会变得非常缓慢
我读过一些关于多处理和矢量化的东西,但我不知道这有多适用,从哪里开始。你可以根据你有多少内核来并行化你的CPU工作。假设你有8个
import threading
import pandas
pool_semaphore = threading.BoundedSemaphore(value=8)
## Define a wrapper function that makes clear the passing of the argument and appends to some list 'result' that I will create later.
def awrapper(myarg):
result.append(paytable.Multiplier.sample(weights = myarg))
threads = []
result = []
for universe in range(10000):
for spins in range(50000):
threads.append(threading.Thread(target=awrapper, args=(paytable.Probability,)))
time.sleep(1)
try:
threads[-1].start()
print(threading.active_count())
except:
time.sleep(1)
print('oops. Error')
for t in threads:
t.join()
现在。如果函数patytable.Multiplier.sample足够简单。您也许可以在GPU中并行化。但那完全是另一回事。
np.random.choice(paytable.multiplier,p=paytable.Probability,shape=(100005000))
?感谢您的回复!我想这会一次抓住所有的值吗?你能解释一下shape=是做什么的吗?