Skip to content

datetime: Speed up timedelta arithmetic by using int64_t directly #162467

Done

Description

@maurycy

Feature or enhancement

For a UTC/aware datetime, datetime_timestamp() subtracts the UNIX epoch and calls total_seconds() on the resulting timedelta. To get the total number of microseconds, delta_to_microseconds() does 2 multiplications and 2 additions on Python integers.

However, days * 86400 + seconds fits in int64_t for every timedelta, so it can be computed in C. (The final multiplication by 10**6 can overflow int64_t for very large deltas, so there'd be still a need for PyLong fallback.)

Benchmark (PGO+LTO, macOS arm64) results:

Operation Before After Speedup
timestamp() on a UTC datetime 95.0 ns 44.2 ns 2.13x
d.total_seconds() (3 days plus fractional seconds) 54.7 ns 23.9 ns 2.25x
d // minus_one_us (divisor of −1 µs) 84.9 ns 26.5 ns 3.20x
total_seconds() on timedelta.max 105.0 ns 74.9 ns 1.40x

Has this already been discussed elsewhere?

No response given

Links to previous discussion of this feature:

No response

Linked PRs

Activity

  1. added
    type-feature
    on Nov 23, 2026
  2. added
    extension-modules
    performance
    on Nov 23, 2026
  3. changed the title [-]`datetime`: Speed up `timedelta.total_seconds()` by using `int64_t` directly[/-] [+]`datetime`: Speed up `timedelta` arithmetic by using `int64_t` directly[/+] on Nov 23, 2026
  4. StanFromIreland commented on Nov 23, 2026

    @StanFromIreland
    Member

    @NekoAsakura all your triage work is great! Just a little suggestion, however, when triaging issues please also try to add them to their respective project if they have one, e.g. the Dates and times project for datetime or time stuff. :-)

  5. added a commit that references this issue on Nov 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesperformancetype-feature

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions