diff options
author | Victor Stinner <victor.stinner@gmail.com> | 2015-04-01 15:47:07 (GMT) |
---|---|---|
committer | Victor Stinner <victor.stinner@gmail.com> | 2015-04-01 15:47:07 (GMT) |
commit | 62d1c70eff9498446d2ce3c564fefee7a7e54770 (patch) | |
tree | a0a7b3f54ed7baa339dfaaeefc048101d727c63c /Python/pytime.c | |
parent | 067bbba7a49aa8bf455465eb5ee75d561cfb1556 (diff) | |
download | cpython-62d1c70eff9498446d2ce3c564fefee7a7e54770.zip cpython-62d1c70eff9498446d2ce3c564fefee7a7e54770.tar.gz cpython-62d1c70eff9498446d2ce3c564fefee7a7e54770.tar.bz2 |
Issue #22117, issue #23485: Fix _PyTime_AsMilliseconds() and
_PyTime_AsMicroseconds() rounding.
Add also unit tests.
Diffstat (limited to 'Python/pytime.c')
-rw-r--r-- | Python/pytime.c | 26 |
1 files changed, 13 insertions, 13 deletions
diff --git a/Python/pytime.c b/Python/pytime.c index 003003b..491bbea 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 |