I’ve found this little function to be useful when dividing work across a fixed number of workers. It does integer division, but rounds up (unlike normal integer division which truncates). Written in python, but it would be easy to write in another language.
def divide_round_up(n, d):
return (n + (d - 1))/d
For example, if we were distributing N jobs to 4 CPU threads, this function will tell us how many total iterations are required to process N threads:
>>> divide_round_up(0,4)
0
>>> divide_round_up(3,4)
1
>>> divide_round_up(4,4)
1
>>> divide_round_up(5,4)
2
>>> divide_round_up(7,4)
2
>>> divide_round_up(8,4)
2
Update: My friend Joe wrote in to say “That has overflow issues if n+d>int_max. How about (n/d)+(bool(n%d))”. For my needs, I’m not going to be anywhere close to int_max, but it’s a valid point.