Closed
Description
Feature or enhancement
Proposal:
According to the existing note # XXX This could be done more efficiently
, the _isoweek1monday
function can be improved.
Current Implementation:
def _isoweek1monday(year):
# Helper to calculate the day number of the Monday starting week 1
# XXX This could be done more efficiently
THURSDAY = 3
firstday = _ymd2ord(year, 1, 1)
firstweekday = (firstday + 6) % 7 # See weekday() above
week1monday = firstday - firstweekday
if firstweekday > THURSDAY:
week1monday += 7
return week1monday
Proposed Change
Replace the current implementation with a simplified logic that is both more performant and easier to understand.
def _isoweek1monday_new(year):
# Calculate the ordinal day of the Monday starting ISO week 1.
# ISO week 1 is defined as the week that contains January 4th.
jan4 = _ymd2ord(year, 1, 4)
jan4_weekday = (jan4 + 6) % 7
return jan4 - jan4_weekday
Rationale
The new logic:
1. Aligns directly with the ISO week definition, which makes it easier to comprehend.
2. Reduces unnecessary computations, improving performance slightly.
Validation and Performance Comparison
Using timeit to compare the current and proposed implementations:
import timeit
from _pydatetime import _isoweek1monday, _ymd2ord
def _isoweek1monday_new(year):
jan4 = _ymd2ord(year, 1, 4)
jan4_weekday = (jan4 + 6) % 7
return jan4 - jan4_weekday
# Validation results:
# >>> all(_isoweek1monday_new(i) == _isoweek1monday(i) for i in range(2000))
# True
# Timing results:
# >>> timeit.timeit('_isoweek1monday(2000)', globals=globals())
# 0.4805744589539245
# >>> timeit.timeit('_isoweek1monday_new(2000)', globals=globals())
# 0.4299807079951279
Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response
Linked PRs
Metadata
Metadata
Assignees
Labels
Projects
Status
Done
Status
Todo