出于好奇,我对这两个功能进行了以下基准测试:
In [12]: %timeit datetime.datetime.now()
100000 loops, best of 3: 5.09 µs per loop
In [13]: %timeit datetime.date.today()
100000 loops, best of 3: 6.4 µs per loop
我认为date
对象涉及的信息较少,所以它应该更快,但结果却更慢。
可能是什么原因?
答案 0 :(得分:1)
我今天被这个书呆子狙击了,所以我会告诉你我的发现 - 带上。
首先,date.today()
的实现必须通过成员函数调用——这个查找似乎是缓慢的部分:
此处摘录:
static PyObject *
date_today(PyObject *cls, PyObject *dummy)
{
PyObject *time;
PyObject *result;
_Py_IDENTIFIER(fromtimestamp);
time = time_time();
if (time == NULL)
return NULL;
/* Note well: today() is a class method, so this may not call
* date.fromtimestamp. For example, it may call
* datetime.fromtimestamp. That's why we need all the accuracy
* time.time() delivers; if someone were gonzo about optimization,
* date.today() could get away with plain C time().
*/
result = _PyObject_CallMethodIdOneArg(cls, &PyId_fromtimestamp, time);
Py_DECREF(time);
return result;
}
值得注意的是它总是通过缓慢的路径
所以我想,为什么不给它一个快速的路径?
$ 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
缩放缩放
$ ./python -m timeit -s 'from datetime import date' 'date.today()'
500000 loops, best of 5: 407 nsec per loop
$ ./python -m timeit -s 'from datetime import datetime' 'datetime.now().date()'
500000 loops, best of 5: 764 nsec per loop
答案 1 :(得分:-1)
我认为datetime.datetime.today()
是datetime.datetime.now()
的一部分或者是{{1}}。我不确定。从“现在”中提取“今天”需要额外的时间。它还取决于硬件和调用进程的时间。您是否接受了很多读数并对其进行了平均测量,或者它的持续时间是否相同?