Skip to content

Commit 8d9d7c9

Browse files
committed
Improve Time.new() performance using division; fix #3561
1 parent 195af52 commit 8d9d7c9

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

mrbgems/mruby-time/src/time.c

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
#include <mruby/class.h>
1212
#include <mruby/data.h>
1313

14+
#define NDIV(x,y) (-(-((x)+1)/(y))-1)
15+
1416
#if _MSC_VER < 1800
1517
double round(double x) {
1618
if (x >= 0.0) {
@@ -237,13 +239,15 @@ time_alloc(mrb_state *mrb, double sec, double usec, enum mrb_timezone timezone)
237239
tm = (struct mrb_time *)mrb_malloc(mrb, sizeof(struct mrb_time));
238240
tm->sec = tsec;
239241
tm->usec = (time_t)llround((sec - tm->sec) * 1.0e6 + usec);
240-
while (tm->usec < 0) {
241-
tm->sec--;
242-
tm->usec += 1000000;
243-
}
244-
while (tm->usec >= 1000000) {
245-
tm->sec++;
246-
tm->usec -= 1000000;
242+
if (tm->usec < 0) {
243+
long sec2 = NDIV(usec,1000000); /* negative div */
244+
tm->usec -= sec2 * 1000000;
245+
tm->sec += sec2;
246+
}
247+
if (tm->usec >= 1000000) {
248+
long sec2 = usec / 1000000;
249+
tm->usec -= sec2 * 1000000;
250+
tm->sec += sec2;
247251
}
248252
tm->timezone = timezone;
249253
time_update_datetime(mrb, tm);

0 commit comments

Comments
 (0)