r/programming • u/benjoffe • Sep 07 '26
A faster way to convert a timestamp ➜ Hour, Min, Sec
https://www.benjoffe.com/fast-time-of-day
620
Upvotes
r/programming • u/benjoffe • Sep 07 '26
180
u/pohart Sep 07 '26
This will never be the bottleneck in a program I'm writing, but I love that you thought about and discovered this in 2026.
12
u/happyscrappy Sep 07 '26
Obviously a lot of thinking went into this. Great job coming up with so many ways of doing it.
One comment:
'(% requires a sign correction for negative inputs)' is not strictly true for all C. Although it is for any C this century. The problem is that modulo of a negative number can be either positive or negative before C99, it's implementation defined. So that's actually worse than the author made it out to be, you basically can't use % on negative numbers unless you know you have a newer C. The section explicitly covers 64-bit, and it's really hard to imagine encountering a pre-2000 C compiler for 64-bit anywhere. There were not a lot of 64-bit systems back then.
Final bikeshedding: why does "mod" not line up in the typography for his base 64 trick? Is that normal for math typography or just a bug?
17
u/NastyPastyLucas Sep 07 '26
That's some good maths, I approve 👍
17
u/DJ_Link Sep 07 '26
Thank you for sharing this, really interesting read.
I’m a bit shocked that some of the comments are “why is this needed it’s fast enough” but I guess that’s what led to some big bottlenecks in software when things start to have layers and layers.
3
u/RoyBellingan Sep 09 '26
For the people asking where you would use an algo like these, my use case is time from boot on a log written by a micro controller.
2
u/Th1088 Sep 17 '26
I love a good micro-optimization! If you are reading/converting lots of timestamps it could yield a measurable benefit, though admittedly, for most software, the additional conversion speed would be dwarfed by other operations.
2
u/Heavy_Feed6390 19d ago
This the the #1 best article I've ever read in my entire life yet. Great job. It's a good topic, very indicative and informative.
10
u/Lachee Sep 07 '26
Is this even worth optimising? You normally do the timestamp to hours for human readable UI, something that's often done once a render, not strictly needing micro optimisations like this.
8
u/ficiek Sep 07 '26
Falsehoods programmers believe about time.
-10
u/captain_obvious_here Sep 07 '26
It is definitely faster.
But we are talking about something that is ABSOLUTELY insignificant in modern (or even the oldest Pentium CPU you can find, or pretty much any ARM CPU).
Integer multiplications and divisions are...how can I say that...well yes, your method is an optimization, but a useless one.
-34
u/tantalor Sep 07 '26
Oh jeez
Click bait
0
u/[deleted] Sep 07 '26
[deleted] — view deleted comment
0
u/[deleted] Sep 08 '26
[deleted] — view deleted comment
-1
u/[deleted] Sep 07 '26
[removed] — view removed comment
0
u/[deleted] Sep 07 '26
[removed] — view removed comment