【发布时间】:2017-05-23 06:38:44
【问题描述】:
在 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()
【问题讨论】:
-
“向我的程序添加功能”不是问题。
-
另外,为
[[], [2, 2, 2], [3, 3], [], [5], [6]]这样的结果存储每个卷似乎毫无意义。为什么不存储每个结果的数量,例如[0, 3, 2, 0, 1, 1]? -
(阅读文档,观看一些视频)重复;尝试实现一些东西;回来提出具体问题。
-
正如@TigerhawkT3 提到的,你真的应该使用更好的数据结构。您可能还应该在 rng 中取出打印,因为无论您在多少个处理器上运行它,打印出数百万个内容都会减慢它的速度。
标签: python python-3.x python-multithreading python-multiprocessing