From 6885d7218090ea626d569f980d4595e4138f72a0 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Mon, 18 May 2020 11:57:16 -0500 Subject: [PATCH] Avoid a context switch in the history api (#35716) * Avoid a context switch in the history api The history api was creating a job to fetch the states and another job to convert the states to json. This can be done in a single job which decreases the overhead of the operation. * Revert to original solution to avoid function redefine each call --- homeassistant/components/history/__init__.py | 28 +++++++++++++++++--- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/history/__init__.py b/homeassistant/components/history/__init__.py index 6fc68b2833e..8d2f9baab81 100644 --- a/homeassistant/components/history/__init__.py +++ b/homeassistant/components/history/__init__.py @@ -298,7 +298,6 @@ class HistoryPeriodView(HomeAssistantView): async def get(self, request, datetime=None): """Return history over a period of time.""" - timer_start = time.perf_counter() if datetime: datetime = dt_util.parse_datetime(datetime) @@ -335,8 +334,29 @@ class HistoryPeriodView(HomeAssistantView): hass = request.app["hass"] - result = await hass.async_add_job( - get_significant_states, + return await hass.async_add_executor_job( + self._sorted_significant_states_json, + hass, + start_time, + end_time, + entity_ids, + include_start_time_state, + significant_changes_only, + ) + + def _sorted_significant_states_json( + self, + hass, + start_time, + end_time, + entity_ids, + include_start_time_state, + significant_changes_only, + ): + """Fetch significant stats from the database as json.""" + timer_start = time.perf_counter() + + result = get_significant_states( hass, start_time, end_time, @@ -363,7 +383,7 @@ class HistoryPeriodView(HomeAssistantView): sorted_result.extend(result) result = sorted_result - return await hass.async_add_job(self.json, result) + return self.json(result) class Filters: