Skip to content

Instantly share code, notes, and snippets.

@methane

methane/mp.py Secret

Created August 31, 2024 07:19
Show Gist options
  • Select an option

  • Save methane/a6cb799704a11f2bb2f64b16c0b830cc to your computer and use it in GitHub Desktop.

Select an option

Save methane/a6cb799704a11f2bb2f64b16c0b830cc to your computer and use it in GitHub Desktop.
import multiprocessing as mp
import numpy
# Array size of 128MiB
size = pow(512, 3)
def fn(array):
return numpy.sum(array)
def multi_process_sum(arr):
# each of 8 processes receives range of 16MiB
c = int(size / 8)
ranges = [(i,i + c) for i in range(0, size, c)]
# create pool of 8 processes
pool = mp.Pool(processes = 4)
# pass each process a part of the array
return int(sum(pool.map(fn, [arr[i:i + c] for i in range(0, size, c)])))
def main():
for _ in range(10):
# Fill array with ones
arr = numpy.ones(size)
# assert sum of all ones is the size, call multiprocessing function
assert(multi_process_sum(arr) == size)
# zero array
arr[0:size] = 0
# assert array is zeroes
assert(multi_process_sum(arr) == 0)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment