Replace datetime::timedelta with custom function#1785
Conversation
Pull Request Test Coverage Report for Build 9018175993Details
💛 - Coveralls |
arkid15r
left a comment
There was a problem hiding this comment.
This would be another win for us on the performance grounds.
After glancing this I wonder if we could use some sort of a lightweight timedelta class version keeping all the syntax (add/radd methods with days support only).
Of course this would make sense if the performance gain doesn't degrade.
@KJhellico do you think it's worth a shot?
|
I tried this, but there is no performance gain. from datetime import date, timedelta
import timeit
class td:
def __init__(self, days: int = 0):
self._days = days
def __radd__(self, other):
if isinstance(other, date):
return date.fromordinal(other.toordinal() + self._days)
return NotImplemented
def __rsub__(self, other):
if isinstance(other, date):
return date.fromordinal(other.toordinal() - self._days)
return NotImplemented
def _start_days(dt: date, n: int) -> date:
return date.fromordinal(dt.toordinal() + n)
def with_timedelta():
dt = date(2024, 1, 1)
d2 = dt + timedelta(days=10)
def with_start_days():
dt = date(2024, 1, 1)
d2 = _start_days(dt, 10)
def with_class_td():
dt = date(2024, 1, 1)
d2 = dt + td(10)
NUM = 10_000_000
t1 = timeit.timeit(with_timedelta, number=NUM)
t2 = timeit.timeit(with_start_days, number=NUM)
t3 = timeit.timeit(with_class_td, number=NUM)
print(f"{NUM} times:")
print(f"timedelta = {t1:.3f}")
print(f"_start_days = {t2:.3f} ({(t2/t1 - 1)*100:.2f}%)")
print(f"class td = {t3:.3f} ({(t3/t1 - 1)*100:.2f}%)")Result: |
arkid15r
left a comment
There was a problem hiding this comment.
I tried this, but there is no performance gain.
Thanks for sharing that! I'd definitely prefer performance over readability here. So our best next step would be to use the function based approach. I have just one naming/flexibility suggestion on this.
The rest LGTM, great PR!
|
Proposed change
Replace
datetime::timedeltawith simple custom function for adding and subtracting days.Performance test script:
Result:
Type of change
Checklist
make pre-commit, it didn't generate any changesmake test, all tests passed locally