Skip to content

gh-162467: Speed up timedelta arithmetic by computing microseconds in int64_t - #162468

Open
maurycy wants to merge 4 commits into
python:mainfrom
maurycy:timedelta-microseconds-c
Open

maurycy wants to merge 4 commits into
python:mainfrom
maurycy:timedelta-microseconds-c

Conversation

@maurycy

@maurycy maurycy commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

delta_to_microseconds() does 2 multiplications and 2 additions on Python ints. days * 86400 + seconds always fits in int64_t, and so does the total in microseconds for all but very large deltas, so it can be computed in C with the existing path kept as a fallback.

PGO+LTO:

Operation Before After
dt.timestamp() (UTC) 95.0 ns 44.2 ns
td.total_seconds() 54.7 ns 23.9 ns
timedelta.max.total_seconds() 105.0 ns 74.9 ns
pyperf benchmark
from datetime import UTC, datetime, timedelta, timezone
import plistlib

import pyperf

dt = datetime(2026, 11, 23, 12, 30, 10, 123456, tzinfo=UTC)
offset_dt = dt.replace(tzinfo=timezone(timedelta(hours=5, minutes=30)))
d = timedelta(days=3, seconds=12345, microseconds=678901)
minus_one_us = timedelta(microseconds=-1)
extreme = timedelta.max

first = datetime(2026, 1, 2, 3, 4, 5, 123456)
dates = [first + timedelta(seconds=i) for i in range(128)]
records = [
    {"id": i, "name": f"item-{i}", "modified": date}
    for i, date in enumerate(dates)
]

runner = pyperf.Runner()
for expr in (
    "dt.timestamp()",
    "d.total_seconds()",
    "d // minus_one_us",
    "extreme.total_seconds()",
    "offset_dt.timestamp()",
    "datetime.now(UTC).timestamp()",
    "plistlib.dumps(dates, fmt=plistlib.FMT_BINARY)",
    "plistlib.dumps(records, fmt=plistlib.FMT_BINARY)",
    "dt.toordinal()",
):
    runner.timeit(expr, expr, globals=globals())

@maurycy maurycy closed this Nov 23, 2026
@maurycy maurycy changed the title timedelta.total_seconds(): int_64 directly gh-162467: Speed up timedelta arithmetic by computing microseconds in int64_t Nov 23, 2026
@bedevere-app bedevere-app Bot added the type-feature A feature request or enhancement label Nov 23, 2026
@maurycy maurycy reopened this Nov 23, 2026

@sergey-miryanov sergey-miryanov left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM, with nits.

Comment thread Modules/_datetimemodule.c Resolved
@StanFromIreland StanFromIreland self-assigned this Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting merge type-feature A feature request or enhancement

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants