Python- 如何让这个程序使用多进程?

Python- How to make this program use multiprocessing?

在python 3、我有一个简单的掷骰子程序。它的作用是询问用户骰子的面数以及他们想掷多少次。

这是通过创建一个列表来实现的,每个子列表代表一个骰子面。每次生成一个随机数,它被附加到相应的子列表。

通过简单的打印程序显示结果。

我的问题是如何使用多处理使其更快,因为完成 100 万次滚动大约需要 21 分钟。

程序代码如下:

import time
import random

roll = []#List for the results

def rng(side,reps):#rolls the dice 
    for i in range(reps):
        land = random.randint(1,side)
        print(land)
        roll[land-1].append(land)

def printR(side,reps):#Prints data
    for i, item in enumerate(roll):
        print('D'+str(i+1),'=''total ',total)

def Main():
    side = int(input('How many sides is the dice'))
    reps = int(input('How many rolls do you want to do?'))

    for i in range(side):#Creates empty arrays corresponding to amount of sides
        roll.append([])

    t0= time.clock()#Start timing dice roller

    rng(side,reps)

    t1 = time.clock()#End timing of dice roller

    printR(side,reps)#Print data
    times  = t1 - t0#Time
    print(round(times,3),'seconds')

Main()

您不需要多处理。你需要做的就是使用更好的算法。

>>> import collections
>>> import random
>>> import time
>>> def f():
...     t = time.perf_counter()
...     print(collections.Counter(random.randint(1,6) for _ in range(1000000)))
...     print(time.perf_counter() - t)
...
>>> f()
Counter({2: 167071, 4: 166855, 3: 166681, 1: 166678, 5: 166590, 6: 166125})
2.207268591399186

选择备用算法可能是最好的方案,但就其价值而言,如果您确实想使用多处理,您可能需要解决不同的问题。例如,假设您有一个数字列表列表。

nums = [[1,2,3],[7,8,9],[4,5,6]]

然后你可以为每个子列表创建一个函数,它可以计算 returns 子集中数字的总和。聚合结果以获得完整的总和,这可能比使用足够大的数据集更快。例如,您也可以进行多道程序合并排序。 Multiprogramming/threading 当您有多个互不干扰且可以单独完成的任务时最好。

对于您最初的问题,您可能必须考虑如何跟踪每侧的总滚动数,以便每侧都有一个函数来计算滚动数,但是通常会出现计算如何计算的问题确保计数器一致/如何知道何时停止。