Skip to content

Commit 3e2ef0d

Browse files
authored
Faster _get_current_state() by 6%-
1 parent 26b8f51 commit 3e2ef0d

File tree

1 file changed

+12
-5
lines changed

1 file changed

+12
-5
lines changed

Modules/_datetimemodule.c

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ static PyTypeObject PyDateTime_TimeZoneType;
3535

3636

3737
typedef struct {
38+
/* Corresponding module */
39+
PyObject *module;
40+
3841
/* Module heap types. */
3942
PyTypeObject *isocalendar_date_type;
4043

@@ -164,12 +167,12 @@ _get_current_state(PyObject **p_mod)
164167
{
165168
PyInterpreterState *interp = PyInterpreterState_Get();
166169
datetime_state *st = interp->datetime_module_state;
167-
if (st != NULL && st->isocalendar_date_type != NULL) {
168-
PyObject *mod = PyType_GetModule(st->isocalendar_date_type);
169-
assert(mod != NULL);
170-
*p_mod = Py_NewRef(mod);
170+
if (st != NULL && st->module != NULL) {
171+
assert(PyModule_CheckExact(st->module));
172+
*p_mod = Py_NewRef(st->module);
171173
return st;
172174
}
175+
173176
PyObject *mod = get_current_module(interp, NULL);
174177
if (mod == NULL) {
175178
assert(!PyErr_Occurred());
@@ -7227,6 +7230,8 @@ create_timezone_from_delta(int days, int sec, int ms, int normalize)
72277230
static int
72287231
init_state(datetime_state *st, PyObject *module, PyObject *old_module)
72297232
{
7233+
st->module = Py_NewRef(module);
7234+
72307235
/* Each module gets its own heap types. */
72317236
#define ADD_TYPE(FIELD, SPEC, BASE) \
72327237
do { \
@@ -7245,6 +7250,7 @@ init_state(datetime_state *st, PyObject *module, PyObject *old_module)
72457250
assert(old_module != module);
72467251
datetime_state *st_old = get_module_state(old_module);
72477252
*st = (datetime_state){
7253+
.module = st->module,
72487254
.isocalendar_date_type = st->isocalendar_date_type,
72497255
.us_per_ms = Py_NewRef(st_old->us_per_ms),
72507256
.us_per_second = Py_NewRef(st_old->us_per_second),
@@ -7304,7 +7310,7 @@ init_state(datetime_state *st, PyObject *module, PyObject *old_module)
73047310
static int
73057311
traverse_state(datetime_state *st, visitproc visit, void *arg)
73067312
{
7307-
/* heap types */
7313+
Py_VISIT(st->module);
73087314
Py_VISIT(st->isocalendar_date_type);
73097315

73107316
return 0;
@@ -7313,6 +7319,7 @@ traverse_state(datetime_state *st, visitproc visit, void *arg)
73137319
static int
73147320
clear_state(datetime_state *st)
73157321
{
7322+
Py_CLEAR(st->module); /* Invalidate first */
73167323
Py_CLEAR(st->isocalendar_date_type);
73177324
Py_CLEAR(st->us_per_ms);
73187325
Py_CLEAR(st->us_per_second);

0 commit comments

Comments
 (0)