This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author Anthony Sottile
Recipients Anthony Sottile
Date 2021-06-04.01:50:33
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1622771434.0.0.798564808537.issue44307@roundup.psfhosted.org>
In-reply-to
Content
```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/
History
Date User Action Args
2021-06-04 01:50:34Anthony Sottilesetrecipients: + Anthony Sottile
2021-06-04 01:50:34Anthony Sottilesetmessageid: <1622771434.0.0.798564808537.issue44307@roundup.psfhosted.org>
2021-06-04 01:50:33Anthony Sottilelinkissue44307 messages
2021-06-04 01:50:33Anthony Sottilecreate