From 7b3ec60f904b441903a0fe1fc1e3fc4212191de9 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Tue, 2 Jan 2024 22:13:23 -1000 Subject: [PATCH] Speed up getting the mean of statistics (#106930) All the values we need to get the mean for are always list[float] so we can use a much simpler algorithm to get the mean of the list --- homeassistant/components/recorder/statistics.py | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/recorder/statistics.py b/homeassistant/components/recorder/statistics.py index 8348933769c..023f94ec88e 100644 --- a/homeassistant/components/recorder/statistics.py +++ b/homeassistant/components/recorder/statistics.py @@ -11,7 +11,6 @@ from itertools import chain, groupby import logging from operator import itemgetter import re -from statistics import mean from typing import TYPE_CHECKING, Any, Literal, TypedDict, cast from sqlalchemy import Select, and_, bindparam, func, lambda_stmt, select, text @@ -145,6 +144,17 @@ STATISTIC_UNIT_TO_UNIT_CONVERTER: dict[str | None, type[BaseUnitConverter]] = { DATA_SHORT_TERM_STATISTICS_RUN_CACHE = "recorder_short_term_statistics_run_cache" +def mean(values: list[float]) -> float | None: + """Return the mean of the values. + + This is a very simple version that only works + with a non-empty list of floats. The built-in + statistics.mean is more robust but is is almost + an order of magnitude slower. + """ + return sum(values) / len(values) + + _LOGGER = logging.getLogger(__name__)