Skip to content

gh-67795: Improve precision of non-float timestamp and timeout arguments - #139273

Merged
serhiy-storchaka merged 12 commits into
python:mainfrom
serhiy-storchaka:timestamp-timeout-as-integer-ratio
Nov 30, 2026
Merged

serhiy-storchaka merged 12 commits into
python:mainfrom
serhiy-storchaka:timestamp-timeout-as-integer-ratio

Conversation

@serhiy-storchaka

@serhiy-storchaka serhiy-storchaka commented Sep 23, 2025 •

Copy link
Copy Markdown
Member

Use the as_integer_ratio() or the numerator and denominator attributes to represent the number as an integer ratio and perform scaling and rounding exactly.

This allows to avoid the precision loss and double rounding error due to conversion to float.


📚 Documentation preview 📚: https://cpython-previews--139273.org.readthedocs.build/

…arguments

Use the as_integer_ratio() or the numerator and denominator attributes
to represent the number as an integer ratio and perform scaling and
rounding exactly.

This allows to avoid the precision loss and double rounding error due to
conversion to float.
@serhiy-storchaka
serhiy-storchaka force-pushed the timestamp-timeout-as-integer-ratio branch from 5672976 to 90f8bf2 Compare September 23, 2025 19:38
Comment thread Python/pytime.c Resolved
Comment thread Python/pytime.c Resolved
serhiy-storchaka and others added 2 commits October 3, 2025 17:58
Co-authored-by: Victor Stinner <vstinner@python.org>
@github-actions

Copy link
Copy Markdown

This PR is stale because it has been open for 30 days with no activity.

@github-actions github-actions Bot added the stale Stale PR or inactive for long period of time. label Apr 29, 2026
@read-the-docs-community

read-the-docs-community Bot commented May 4, 2026 •

Copy link
Copy Markdown

@github-actions github-actions Bot removed the stale Stale PR or inactive for long period of time. label May 16, 2026
@github-actions

Copy link
Copy Markdown

This PR is stale because it has been open for 90 days with no activity.

@github-actions github-actions Bot added the stale Stale PR or inactive for long period of time. label Aug 18, 2026
@edgarrmondragon

Copy link
Copy Markdown
Contributor

I'd love to see this in 3.16 so it'd be a shame for it to go stale

@github-actions github-actions Bot removed the stale Stale PR or inactive for long period of time. label Aug 23, 2026
@github-actions

Copy link
Copy Markdown

This PR is stale because it has been open for 90 days with no activity.

@github-actions github-actions Bot added the stale Stale PR or inactive for long period of time. label Nov 27, 2026

@vstinner vstinner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be possible to add some C API tests to test_time?

  • test_object_to_time_t(): _PyTime_ObjectToTime_t()
  • test_object_to_timeval(): _PyTime_ObjectToTimeval()
  • test_object_to_timespec(): _PyTime_ObjectToTimespec()

Or I can try to add some tests once this change will be merged.

Comment thread Python/pytime.c Resolved
Comment thread Python/pytime.c Resolved
Comment thread Python/pytime.c Resolved
Comment thread Python/pytime.c Resolved
Comment thread Doc/whatsnew/3.15.rst Resolved
serhiy-storchaka and others added 4 commits November 27, 2026 15:19
…s-integer-ratio

# Conflicts:
#	Include/internal/pycore_global_objects_fini_generated.h
#	Include/internal/pycore_unicodeobject_generated.h
Also simplify checked_divmod() and clarify the comment of
maybe_as_integer_ratio().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…yTime_ObjectToTimespec()

The rounding mode was ignored: the fractional part was always rounded
half to even.

Add tests for conversion of Fraction, Decimal and other numbers with
the numerator and denominator attributes in the C API.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Only the remainder of the division by the denominator is now scaled,
as in _PyTime_ObjectToTimeval() and _PyTime_ObjectToTimespec().
Too large values are rejected before the multiplication.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
serhiy-storchaka and others added 2 commits November 27, 2026 16:26
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@serhiy-storchaka serhiy-storchaka left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added tests. They found a bug: the rounding mode was ignored in _PyTime_ObjectToTimeval() and _PyTime_ObjectToTimespec(). Fixed.

Comment thread Python/pytime.c Resolved
Comment thread Python/pytime.c Resolved
Comment thread Python/pytime.c Resolved
Comment thread Python/pytime.c Resolved
Comment thread Doc/whatsnew/3.15.rst Resolved

@vstinner vstinner left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. I'm feeling safer with new tests in test_time :-)

Comment thread Python/pytime.c Outdated
*ratio = NULL;
if (PyType_Check(number)) {
PyErr_SetString(PyExc_TypeError,
"required a number, not type");

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
"required a number, not type");
"expected a number, not type");

"required" reads a little oddly.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed to must be real number, not %T, the same as the error for other non-numbers.

Comment thread Python/pytime.c Outdated
Py_DECREF(ratio);
return -1;
}
PyTime_t ns;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: ns holds whole seconds or milliseconds until the pytime_mul() below, which is confusing next to unit_to_ns. Maybe units?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.

@serhiy-storchaka

Copy link
Copy Markdown
Member Author

Performance impact: int and float are not affected. For a timestamp with nanosecond precision (19 digits), converting a Decimal is about 140 ns slower and a Fraction about 70 ns slower, because of the as_integer_ratio() call and integer arithmetic, but the result is now correctly rounded. For functions like time.sleep() this is negligible compared to the system call, but it is noticeable in datetime.fromtimestamp(): 371 → 569 ns for Decimal (+53%) and 296 → 397 ns for Fraction (+34%).

@vstinner

Copy link
Copy Markdown
Member

IMO the performance slowdown is accepted and worth it.

Passing Fraction and Decimal as timestamp sounds like an unusual use case. I suppose that if someone does that, it would be to get the best accuracy, not for the best performance.

There is already a workaround for performance: use float or int.

If later, performance becomes too critical, we may add new functions. For example, add time.sleep_ns(int) which sleeps a number of nanoseconds (integer).

@StanFromIreland StanFromIreland left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

I wonder how long till the PSRT will get a report about this performance change. ;-)

@serhiy-storchaka
serhiy-storchaka merged commit f4b3d2b into python:main Nov 30, 2026
59 checks passed
@serhiy-storchaka
serhiy-storchaka deleted the timestamp-timeout-as-integer-ratio branch November 30, 2026 09:29
@hugovk

hugovk commented Nov 30, 2026

Copy link
Copy Markdown
Member

Looks like this is failing for 32-bit:

ERROR: test_object_to_timespec (test.test_time.TestOldPyTime.test_object_to_timespec)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/var/lib/buildbot/workers/3.x.gps-raspbian.nondebug/build/Lib/test/test_time.py", line 1349, in test_object_to_timespec
    self.check_ratio_rounding(_PyTime_ObjectToTimespec,
    ~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^
                              lambda units: divmod(units, SEC_TO_NS),
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
                              SEC_TO_NS,
                              ^^^^^^^^^^
                              value_filter=self.time_t_filter)
                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/var/lib/buildbot/workers/3.x.gps-raspbian.nondebug/build/Lib/test/test_time.py", line 1085, in check_ratio_rounding
    self.assertEqual(pytime_converter(value, time_rnd),
                     ~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
OverflowError: timestamp out of range for platform time_t

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

stale Stale PR or inactive for long period of time.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants