Sort.py
import random import time def time_analysis(func): def do_func(*args, **kwargs): print('[INFO] \'{}\' analysis started (N={}).'.format(func.__name__, len(args[0]))) start_time = time.clock() result = func(*args, **kwargs) end_time = time.clock() total_time = end_time - start_time print('[INFO] \'{}\' took {} seconds (N={}).'.format(func.__name__, total_time, len(args[0]))) return result return do_func @time_analysis def bubble_sort(num_list): num_len = len(num_list) for i in range(num_len - 1): for j in range(num_len - i - 1): if num_list[j] > num_list[j + 1]: num_list[j], num_list[j + 1] = num_list[j + 1], num_list[j] return num_list if __name__ == '__main__': N = 30000 random_list = list(range(N)) random.shuffle(random_list) bubble_sort(random_list) random_list = list(range(N)) random.shuffle(random_list) bubble_sort(random_list) Parallel.py
from multiprocessing import Pool, cpu_count from Sort import * def bubble_sort_parallel(*args, **kwargs): return bubble_sort(*args, **kwargs) if __name__ == '__main__': N = 30000 random_list = list(range(N)) random.shuffle(random_list) pool.apply_async(bubble_sort_parallel, (random_list,)) random_list = list(range(N)) random.shuffle(random_list) pool.apply_async(bubble_sort_parallel, (random_list,)) pool.close() pool.join() Single thread took only 2 seconds but Multiprocessing took 8 seconds.
N = 300,000. Single thread took only 200 seconds but Multiprocessing took 1400 seconds.
Why using multiprocessing is slower than single thread?
How could I improve the performance?
Platform: Linux, pypy2.7-5.10.0, 4 Cores on my computer
Multiprocessing: [Figure of multiprocessing][https://i.sstatic.net/QksXf.png]
Single thread: [Figure of single thread][https://i.sstatic.net/9HYw7.png]
Sort.pyon its own, I getTypeError: object of type 'NoneType' has no len(). Is that intended? How are you getting the timing of the single threaded approach?random.shufflereturns None, so that may be impacting your runtime: you're not actually passing a list to your sorting functions.