Skip to content

Speed up datetime.timedelta construction for the common all-integer case #150716

@gaborbernat

Description

@gaborbernat

Feature or enhancement

Callers usually build datetime.timedelta from whole numbers of seconds, minutes, or days. That common case runs through the same construction path as float and other arguments, slower than it needs to be for plain integers.

Code that creates timedeltas in bulk pays for it:

  • A pipeline computing a duration per row over millions of rows with timedelta(seconds=value).
  • A scheduler assigning intervals to thousands of jobs with timedelta(minutes=n).
  • Retry logic computing timedelta(seconds=2 ** attempt) in a loop.
  • Config loaders expanding numeric settings into timedelta objects.

Proposed change: when every argument is a whole number, compute the result directly. Other inputs (float, bool, int subclasses, values too large to fit) keep the current path, so results and error messages stay the same.

This matches the datetime fast path from gh-88473, which special-cases date.today() for exact date and leaves other cases alone.

On a local optimized build, integer construction runs 47 to 62 percent faster across the common shapes (no arguments, seconds=, days=, mixed, negative, weeks=). Float and other cases stay unchanged. A reference check over hundreds of thousands of argument combinations, including overflowing ones, found no differences.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    extension-modulesC modules in the Modules dirperformancePerformance or resource usagetype-featureA feature request or enhancement
    No fields configured for issues without a type.

    Projects

    Status
    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions