如何让这个程序使用多处理? [英] Python- How to make this program use multiprocessing?

查看:17
本文介绍了如何让这个程序使用多处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在python3中,我有一个简单的掷骰子程序。它所做的是询问用户骰子的边数以及他们想要掷几次骰子。

这是通过创建一个列表来实现的,每个子列表代表一个骰子面。每次生成随机数时,都会将其追加到相应的子列表中。

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

我的问题是如何使用多处理来提高速度,因为做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

这篇关于如何让这个程序使用多处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆