From e09e4f14d6dfc1974dce8318976d0258936619f3 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Thu, 25 May 2023 07:34:07 -0500 Subject: [PATCH] Speed up setting state (#93472) --- homeassistant/core.py | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/homeassistant/core.py b/homeassistant/core.py index b2a00cce038..747affef76f 100644 --- a/homeassistant/core.py +++ b/homeassistant/core.py @@ -25,6 +25,7 @@ import os import pathlib import re import threading +import time from time import monotonic from typing import ( TYPE_CHECKING, @@ -1620,10 +1621,24 @@ class StateMachine: if same_state and same_attr: return - now = dt_util.utcnow() - if context is None: - context = Context(id=ulid_util.ulid_at_time(dt_util.utc_to_timestamp(now))) + # It is much faster to convert a timestamp to a utc datetime object + # than converting a utc datetime object to a timestamp since cpython + # does not have a fast path for handling the UTC timezone and has to do + # multiple local timezone conversions. + # + # from_timestamp implementation: + # https://github.com/python/cpython/blob/c90a862cdcf55dc1753c6466e5fa4a467a13ae24/Modules/_datetimemodule.c#L2936 + # + # timestamp implementation: + # https://github.com/python/cpython/blob/c90a862cdcf55dc1753c6466e5fa4a467a13ae24/Modules/_datetimemodule.c#L6387 + # https://github.com/python/cpython/blob/c90a862cdcf55dc1753c6466e5fa4a467a13ae24/Modules/_datetimemodule.c#L6323 + timestamp = time.time() + now = dt_util.utc_from_timestamp(timestamp) + context = Context(id=ulid_util.ulid_at_time(timestamp)) + else: + now = dt_util.utcnow() + state = State( entity_id, new_state,