New submission from Anthony Sottile <asott...@umich.edu>:
```console $ python3.10 -m timeit -s 'from datetime import datetime' 'datetime.now().date()' 500000 loops, best of 5: 708 nsec per loop $ python3.10 -m timeit -s 'from datetime import date' 'date.today()' 200000 loops, best of 5: 1.4 usec per loop ``` this surprised me so I dug into it -- it appears a fast path can be added to `date.today()` to make it faster than `datetime.date.now()` -- though I'm rather unfamiliar with the functions involved here here is my ~sloppy patch attempting to add a fast path, I would need some guidance to improve it and get it accepted: ```diff $ git diff -w diff --git a/Modules/_datetimemodule.c b/Modules/_datetimemodule.c index 8ef2dad37a..7eaa5d1740 100644 --- a/Modules/_datetimemodule.c +++ b/Modules/_datetimemodule.c @@ -2875,6 +2875,17 @@ date_fromtimestamp(PyObject *cls, PyObject *obj) static PyObject * date_today(PyObject *cls, PyObject *dummy) { + /* fast path, don't call fromtimestamp */ + if ((PyTypeObject *)cls == &PyDateTime_DateType) { + struct tm tm; + time_t t; + time(&t); + localtime_r(&t, &tm); + return new_date_ex(tm.tm_year + 1900, + tm.tm_mon + 1, + tm.tm_mday, + (PyTypeObject*)cls); + } else { PyObject *time; PyObject *result; _Py_IDENTIFIER(fromtimestamp); @@ -2893,6 +2904,7 @@ date_today(PyObject *cls, PyObject *dummy) Py_DECREF(time); return result; } +} /*[clinic input] @classmethod ``` after this, `date.today()` is faster! ```console $ ./python -m timeit -s 'from datetime import datetime' 'datetime.now().date()' 500000 loops, best of 5: 764 nsec per loop $ ./python -m timeit -s 'from datetime import date' 'date.today()' 500000 loops, best of 5: 407 nsec per loop ``` \o/ ---------- components: Extension Modules messages: 395061 nosy: Anthony Sottile priority: normal severity: normal status: open title: date.today() is 2x slower than datetime.now().date() type: performance versions: Python 3.11 _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue44307> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com