Follow @Openwall on Twitter for new release announcements and other news
[<prev] [next>] [thread-next>] [day] [month] [year] [list]
Message-ID: <2657da91-29d8-4014-ad11-1c31bc890b1d@gmail.com>
Date: Tue, 26 Aug 2025 14:42:00 +0300
From: Alexey Moiseytsev <himeraster@...il.com>
To: musl@...ts.openwall.com
Subject: [PATCH] __secs_to_tm: replace the linear search with a closed-form
 integer formula

Replace the sequential subtraction loop with a fixed-point month-index calculation to speed up month lookup.
The month index is computed using a reciprocal 2^14/535 ≈ 30.62 (close to the mean month length); the small bias 333 is chosen to provide correct rounding.
The day-of-month is recovered with (979*months + 16) >> 5, which yields the cumulative month starts [0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 337] (March-first).
Microbenchmarks for the gmtime_r function show up to 1.5-2 times speed up depending on CPU model.

Signed-off-by: Alexey Moiseytsev <himeraster@...il.com>
---
 src/time/__secs_to_tm.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)

diff --git a/src/time/__secs_to_tm.c b/src/time/__secs_to_tm.c
index 093d9021..2a266dbf 100644
--- a/src/time/__secs_to_tm.c
+++ b/src/time/__secs_to_tm.c
@@ -15,7 +15,6 @@ int __secs_to_tm(long long t, struct tm *tm)
 	int qc_cycles, c_cycles, q_cycles;
 	int months;
 	int wday, yday, leap;
-	static const char days_in_month[] = {31,30,31,30,31,31,30,31,30,31,31,29};

 	/* Reject time_t values whose year would overflow int */
 	if (t < INT_MIN * 31622400LL || t > INT_MAX * 31622400LL)
@@ -57,8 +56,8 @@ int __secs_to_tm(long long t, struct tm *tm)

 	years = remyears + 4*q_cycles + 100*c_cycles + 400LL*qc_cycles;

-	for (months=0; days_in_month[months] <= remdays; months++)
-		remdays -= days_in_month[months];
+	months = (remdays * 535 + 333) >> 14;
+	remdays -= (979 * months + 16) >> 5;

 	if (months >= 10) {
 		months -= 12;
-- 
2.34.1

Powered by blists - more mailing lists

Confused about mailing lists and their use? Read about mailing lists on Wikipedia and check out these guidelines on proper formatting of your messages.