Avoid additional timestamp conversion to set state (#118885)

Avoid addtional timestamp conversion to set state

Since we already have the timestamp, we can pass it on to the State
object and avoid the additional timestamp conversion which can be as
much as 30% of the state write runtime.

Since datetime objects are limited to microsecond precision, we need
to adjust some tests to account for the additional precision that we
will now be able to get in the database
This commit is contained in:
J. Nick Koston
2024-06-05 22:43:34 -05:00
committed by GitHub
parent 475c20d529
commit f9205cd88d
5 changed files with 332 additions and 143 deletions

View File

@ -1762,6 +1762,7 @@ class State:
context: Context | None = None,
validate_entity_id: bool | None = True,
state_info: StateInfo | None = None,
last_updated_timestamp: float | None = None,
) -> None:
"""Initialize a new state."""
state = str(state)
@ -1793,7 +1794,8 @@ class State:
# so we will set the timestamp values here to avoid the overhead of
# the function call in the property we know will always be called.
last_updated = self.last_updated
last_updated_timestamp = last_updated.timestamp()
if not last_updated_timestamp:
last_updated_timestamp = last_updated.timestamp()
self.last_updated_timestamp = last_updated_timestamp
if self.last_changed == last_updated:
self.__dict__["last_changed_timestamp"] = last_updated_timestamp
@ -2309,6 +2311,7 @@ class StateMachine:
context,
old_state is None,
state_info,
timestamp,
)
if old_state is not None:
old_state.expire()