Python- How to make this program use multiprocessing?(如何让这个程序使用多处理?)
本文介绍了如何让这个程序使用多处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在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
这篇关于如何让这个程序使用多处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:如何让这个程序使用多处理?


基础教程推荐
猜你喜欢
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01