I'm trying to divide a task between all cores of a CPU. I'm doing this basically as the code below. I have, for example, a grid that has 80 elements and I have 8 cores in my CPU. For each element of the grid, I need to do a calculation, for this case, It will be 10 calculations for each core. The code is running, but It is not having the development I'm wanting, the max usage of CPU I'm having is 50%, but most of the time It stays at 25-30%. How can I make this code runs faster? How can I get more usage of a CPU?
from multiprocessing import Process, cpu_count
def initialize(info):
my_object = my_class(info)
grid = my_object.get_grid()
core_amount = cpu_count()
var_aux, start_index, end_index = 0, 0, 0
processes = []
while var_aux <= core_amount:
# these if/elif is just to determinate the start and end index of the calculation for each core job
if var_aux < core_amount:
relation = floor(len(grid)/core_amount)
start_index = relation * var_aux
end_index = relation * (var_aux + 1)
elif var_aux == core_amount:
start_index = floor(len(grid)/core_amount) * var_aux
end_index = len(grid)
if start_index != end_index:
processes.append(Process(target = partial_calculation, args=(my_object, grid, start_index, end_index )))
processes[var_aux].start()
var_aux += 1
for process in processes:
process.join()
return my_object
def partial_calculation(my_class_object, grid, start_index, end_index): #this is the method that is called in parallel
while start_index < end_index:
my_class_object.make_calculation(grid[start_index]) #Here is the calculation of a grid state
start_index += 1
if __name__ == '__main__':
info = something()
my_object = initialize(info)
my_object.use_it_after_calculation_is_done()
I hope I was clear, thanks!