Skip to content

Instantly share code, notes, and snippets.

@adilkhash
Created March 15, 2023 04:49
Show Gist options
  • Save adilkhash/c8200fd7e2144a4fe3d3effb71dc991a to your computer and use it in GitHub Desktop.
Save adilkhash/c8200fd7e2144a4fe3d3effb71dc991a to your computer and use it in GitHub Desktop.
import time
from multiprocessing import Process, Value
from multiprocessing import Pool
def sum_numbers(numbers):
result = 0
for number in numbers:
result += number
return result
def sum_numbers_shared(numbers, shared_sum):
for number in numbers:
shared_sum.value += number
if __name__ == '__main__':
numbers = list(range(1, 100_000))
start_time = time.time()
sum_without_multiprocessing = sum_numbers(numbers)
end_time = time.time()
print(f'Sum without multiprocessing: {sum_without_multiprocessing}')
print(f'Time without multiprocessing: {end_time - start_time}')
shared_sum = Value('i', 0)
start_time = time.time()
p = Process(target=sum_numbers_shared, args=(numbers, shared_sum))
p.start()
p.join()
sum_with_shared_memory = shared_sum.value
end_time = time.time()
print(f'Sum with shared memory: {sum_with_shared_memory}')
print(f'Time with shared memory: {end_time - start_time}')
pool = Pool(processes=4)
start_time = time.time()
sum_with_multiprocessing = sum(pool.map(sum_numbers, [numbers[i::4] for i in range(4)]))
end_time = time.time()
print(f'Sum with multiprocessing: {sum_with_multiprocessing}')
print(f'Time with multiprocessing: {end_time - start_time}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment