print_number() - an alternative for sprintf()

Probably premature optimization, but if you need that extra ounce of efficiency converting numbers to ascii, here's print_number(): 9.27 seconds against sprintf's 22.88, with optional zero-padding and a returned pointer to the char right after the number. Enjoy.

In most situations this probably falls clearly into the category of premature optimization, but if you need that extra ounce of efficiency in a situation where you're converting a numeric value into its ascii equivalent via sprintf(), you might find this print_number() solution useful.

It has precisely one feature beyond simply ascii-fying numbers, and that is adding an optional zero-padding; printing "123" with five places of zero padding results in "00123", which you could accomplish like this:

char output[6] = { 0 };
print_number(output, 123, 5);


So, here are the performance characteristics when printing 0..100,000,000 with eight-digit zero-padding (in microseconds):

int main(int, const char **).. test1=9273221, test2=22877905

That's 9.27 seconds for print_number() and 22.88 seconds for sprintf().

Oh, perhaps this could be considered a 2nd feature. print_number() returns a pointer to the char immediately following the end of the number it just printed. It saves you a step in a situation like this:

char output[n];
char *output_ptr = output;
output_ptr = print_number(output_ptr, 1, 5);
output_ptr = print_number(output_ptr, 2, 5);
output_ptr = print_number(output_ptr, 3, 5);

Etc. You don't have to explicitly increment the pointer each time since that value is returned.
Enjoy.

Subscribe to A garage sale for your mind

Don’t miss out on the latest posts. Sign up now to get access to the library of members-only posts.
[email protected]
Subscribe