Created
October 7, 2019 16:17
-
-
Save florisvb/8148ef418edcf7794716e60f3a9918b7 to your computer and use it in GitHub Desktop.
multiprocessing example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import multiprocessing | |
import numpy as np | |
import time | |
def compute_something(input): | |
a = input[0] | |
b = input[1] | |
r = a**b**b | |
return r | |
if __name__ == '__main__': | |
inputs = [[np.random.randint(1,10), np.random.randint(1,7)] for i in range(1000)] | |
# not parallel: | |
t_start = time.time() | |
r = [compute_something(inp) for inp in inputs] | |
print('Not parallel: ' + str(time.time() - t_start) + ' sec') | |
# parallel: | |
ncores = int(0.9*multiprocessing.cpu_count()) | |
t_start = time.time() | |
pool = multiprocessing.Pool(ncores) | |
r = pool.map(compute_something, inputs) | |
print('Parallel: ' + str(time.time() - t_start) + ' sec, with ' + str(ncores) + ' cpu cores') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment