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 编写 Fortran 无格式文件 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
