如何提高程序中嵌套循环的速度?

2024-06-07 00:13:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我在玩老虎机模拟器Code

程序的核心是一个嵌套循环,如下所示:

import pandas

for universe in range(10000):
    for spins in range(50000):
        win = paytable.Multiplier.sample(weights=paytable.Probability)
        result.append(win)

宇宙是应该模拟下注过程的次数

自旋是每个宇宙中的自旋数量

该程序从熊猫数据帧中进行加权选择,以确定旋转是否获胜以及获胜多少

问题是我需要执行所有这些操作以获得足够大的样本量,而这会变得非常缓慢

我读过一些关于多重处理和矢量化的东西,但我不知道这有多适用,从哪里开始


Tags: inimport程序pandas核心forcoderange
1条回答
网友
1楼 · 发布于 2024-06-07 00:13:12

你可以根据你有多少内核来并行化你的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中并行化。但那完全是另一回事

相关问题 更多 >