Skip to content Skip to sidebar Skip to footer

Multithread Vs List Comprehension In Simulation

Suppose we have a recurrence relation A[0] = a A[i+1] = f(A[i],c) where c is a parameter and f is some function, say def f(x, c): return sin(x) + c Assume that, for a given

Solution 1:

I would prefer using the Pool wrapper as it definitely seems to be better the thread approach. Try this:

from multiprocessing import Pool
import numpy as np

def f(x, c):
    return sin(x)+c

A = np.zeros(shape=(m, n))
for i in range(n-1):
    pool = Pool()
    res = []
    for j in range(m):
        res.append(pool.apply_async(f, (A[i, j], Cs[j])))
    pool.close()
    pool.join()
    for j in range(m):
        A[i+1, j] = res[j].get()

You can always time the two approaches and see which one is the fastest with:

 import time
 start_time = time.time()
 # your code
 print("%.6f seconds" % (time.time() - start_time))

It is not very accurate, but it should be enough for your purpose.

Post a Comment for "Multithread Vs List Comprehension In Simulation"