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:
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.
I spend a lot of time write and debugging command line scripts and programs. As much as I like looking at large numbers (millions, billions, trillions, etc) it can be difficult to read a big number and quickly parse how large it is, i.e. “is that 12 megabytes or 1.2 gigabytes?”.
A long time ago I wrote a small function that does pretty printing of a number of bytes. It can handle from bytes to exabytes, and properly handles integer numbers of a unit by printing it as an integer instead of float. Should be easy enough to adjust to your specific needs or style desires.
// Prints to the provided buffer a nice number of bytes (KB, MB, GB, etc)
void pretty_bytes(char* buf, uint bytes)
const char* suffixes;
suffixes = "B";
suffixes = "KB";
suffixes = "MB";
suffixes = "GB";
suffixes = "TB";
suffixes = "PB";
suffixes = "EB";
uint s = 0; // which suffix to use
double count = bytes;
while (count >= 1024 && s < 7)
count /= 1024;
if (count - floor(count) == 0.0)
sprintf(buf, "%d %s", (int)count, suffixes[s]);
sprintf(buf, "%.1f %s", count, suffixes[s]);