Skip to content

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

Open

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. 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
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-modulesC modules in the Modules dirperformancePerformance or resource usagetype-featureA feature request or enhancement

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions