From 62d1c70eff9498446d2ce3c564fefee7a7e54770 Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Wed, 1 Apr 2015 17:47:07 +0200 Subject: Issue #22117, issue #23485: Fix _PyTime_AsMilliseconds() and _PyTime_AsMicroseconds() rounding. Add also unit tests. --- Python/pytime.c | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) (limited to 'Python/pytime.c') diff --git a/Python/pytime.c b/Python/pytime.c index 003003bdca..491bbea611 100644 --- a/Python/pytime.c +++ b/Python/pytime.c @@ -19,6 +19,10 @@ #define MS_TO_NS (MS_TO_US * US_TO_NS) #define SEC_TO_NS (SEC_TO_MS * MS_TO_NS) +/* Conversion from nanoseconds */ +#define NS_TO_MS (1000 * 1000) +#define NS_TO_US (1000) + static void error_time_t_overflow(void) { @@ -288,33 +292,29 @@ _PyTime_AsNanosecondsObject(_PyTime_t t) } static _PyTime_t -_PyTime_Multiply(_PyTime_t t, unsigned int multiply, _PyTime_round_t round) +_PyTime_Divide(_PyTime_t t, _PyTime_t k, _PyTime_round_t round) { - _PyTime_t k; - if (multiply < SEC_TO_NS) { - k = SEC_TO_NS / multiply; - if (round == _PyTime_ROUND_CEILING) + assert(k > 1); + if (round == _PyTime_ROUND_CEILING) { + if (t >= 0) return (t + k - 1) / k; else - return t / k; - } - else { - k = multiply / SEC_TO_NS; - return t * k; + return (t - (k - 1)) / k; } + else + return t / k; } _PyTime_t _PyTime_AsMilliseconds(_PyTime_t t, _PyTime_round_t round) { - return _PyTime_Multiply(t, 1000, round); + return _PyTime_Divide(t, NS_TO_MS, round); } -/* FIXME: write unit tests */ _PyTime_t _PyTime_AsMicroseconds(_PyTime_t t, _PyTime_round_t round) { - return _PyTime_Multiply(t, 1000 * 1000, round); + return _PyTime_Divide(t, NS_TO_US, round); } static int -- cgit v1.2.1