[v3,2/2] Use modulo instead of mul+sub in __secs_to_tm

Submitted by Mattias Andrée on Feb. 28, 2021, 7:27 p.m.

Details

Message ID 20210228192712.1666688-2-maandree@kth.se
State New
Series "Remove unnecessary if in __secs_to_tm"
Headers show

Commit Message

Mattias Andrée Feb. 28, 2021, 7:27 p.m.
On x86 modulo is free when doing division, so this removes
a multiplication and at the cost of replacing a conditional
move with a conditional jump, but it still appears to be
faster.
(Similar architectures: nds32le)

ARM doesn't have modulo, instead an multiply-and-subtract
operation is done after the division, so the diffence
here is either none at all, or a move and a multiply-and-add
being replaced with a multiply-and-subtract.
(Similar architectures: or1k)

RISC-V on the other hand has a separate modulo
instruction and will perform a separate modulo instead of
an assignment, a multiplication, and an addition with
this change. GCC does change how the modulo operation is
realised depending on the optimisation level. I don't know
how this affects the performance, however a simple test on
x86 suggests that doing a modulo operations is actually
faster than assign–multiply–add.
---
 src/time/__secs_to_tm.c | 16 +++++++++++-----
 1 file changed, 11 insertions(+), 5 deletions(-)

Patch hide | download patch | download mbox

diff --git a/src/time/__secs_to_tm.c b/src/time/__secs_to_tm.c
index 62219df5..59b1fc8d 100644
--- a/src/time/__secs_to_tm.c
+++ b/src/time/__secs_to_tm.c
@@ -40,15 +40,21 @@  int __secs_to_tm(long long t, struct tm *tm)
 	}
 
 	c_cycles = remdays / DAYS_PER_100Y;
-	if (c_cycles == 4) c_cycles--;
-	remdays -= c_cycles * DAYS_PER_100Y;
+	remdays %= DAYS_PER_100Y;
+	if (c_cycles == 4) {
+		remdays += DAYS_PER_100Y;
+		c_cycles--;
+	}
 
 	q_cycles = remdays / DAYS_PER_4Y;
-	remdays -= q_cycles * DAYS_PER_4Y;
+	remdays %= DAYS_PER_4Y;
 
 	remyears = remdays / 365;
-	if (remyears == 4) remyears--;
-	remdays -= remyears * 365;
+	remdays %= 365;
+	if (remyears == 4) {
+		remdays += 365;
+		remyears--;
+	}
 
 	leap = !remyears && (q_cycles || !c_cycles);
 	yday = remdays + 31 + 28 + leap;