Skip to content Skip to sidebar Skip to footer

Python- How To Make This Program Use Multiprocessing?

In python 3, I have a simple dice roller program. What it does is ask the user for the amount of sides of a dice and how many times they would like to roll it. This is accomplished

Solution 1:

You don't need multiprocessing. All you need to do is use a better algorithm.

>>>import collections>>>import random>>>import time>>>deff():...    t = time.perf_counter()...print(collections.Counter(random.randint(1,6) for _ inrange(1000000)))...print(time.perf_counter() - t)...>>>f()
Counter({2: 167071, 4: 166855, 3: 166681, 1: 166678, 5: 166590, 6: 166125})
2.207268591399186

Solution 2:

Choosing the alternate algorithm is probably the best plan, but for what it's worth, if you did want to use multiprocessing, you'd probably have a different problem to solve. For example, let's say you had a list of lists of numbers.

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

Then you could have a function per-sub-list that maybe calculates and returns the sum of the numbers in the sub-set. Aggregate the results to get the full sum, probably more quickly than you would otherwise with a large enough data set. You could have a multiprogramming merge sort too, for example. Multiprogramming/threading is best when you have a number of tasks that don't interfere with each other and can be completed in isolation.

For your original problem, you'd probably have to think about how to keep track of total rolls per side so you could have a function per side calculating rolls, but then there would be the usual issue of figuring how to make sure counters are consistent / how to know when to stop.

Post a Comment for "Python- How To Make This Program Use Multiprocessing?"