Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何提高程序中嵌套循环的速度?_Python_Pandas_Performance_Optimization_Multiprocessing - Fatal编程技术网

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=是做什么的吗?