【问题标题】:Python- How to make this program use multiprocessing? [closed]Python-如何让这个程序使用多处理? [关闭]
【发布时间】: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


【解决方案1】:

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

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

然后你可以有一个函数 per-sub-list 可以计算并返回子集中数字的总和。聚合结果以获得完整的总和,可能比使用足够大的数据集更快。例如,您也可以进行多道程序合并排序。多道程序/线程处理是最好的,当您有许多相互不干扰并且可以单独完成的任务时。

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

【讨论】:

    【解决方案2】:

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

    >>> 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-03
      • 2020-08-31
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 2017-11-19
      相关资源
      最近更新 更多