Optimize event matcher (#9798)

* Optimize event matcher

* Tweak order of checks

* Add a benchmark for time_changed helper

* Add state change benchmark

* fix lint
This commit is contained in:
Paulus Schoutsen authored and Pascal Vizeli committed 2017-10-10 22:26:03 +02:00
1 parent a97e7bb22d
commit 8f06b35dfc
3 files changed
+104 -43

No files matched your search

+74 -2
View File
@@ -2,10 +2,14 @@
import asyncio
import argparse
from contextlib import suppress
from datetime import datetime
import logging
from timeit import default_timer as timer
from homeassistant.const import (
EVENT_TIME_CHANGED, ATTR_NOW, EVENT_STATE_CHANGED)
from homeassistant import core
from homeassistant.util import dt as dt_util
BENCHMARKS = {}
@@ -64,11 +68,79 @@ def async_million_events(hass):
hass.bus.async_listen(event_name, listener)
start = timer()
for _ in range(10**6):
hass.bus.async_fire(event_name)
start = timer()
yield from event.wait()
return timer() - start
@benchmark
@asyncio.coroutine
# pylint: disable=invalid-name
def async_million_time_changed_helper(hass):
"""Run a million events through time changed helper."""
count = 0
event = asyncio.Event(loop=hass.loop)
@core.callback
def listener(_):
"""Handle event."""
nonlocal count
count += 1
if count == 10**6:
event.set()
hass.helpers.event.async_track_time_change(listener, minute=0, second=0)
event_data = {
ATTR_NOW: datetime(2017, 10, 10, 15, 0, 0, tzinfo=dt_util.UTC)
}
for _ in range(10**6):
hass.bus.async_fire(EVENT_TIME_CHANGED, event_data)
start = timer()
yield from event.wait()
return timer() - start
@benchmark
@asyncio.coroutine
# pylint: disable=invalid-name
def async_million_state_changed_helper(hass):
"""Run a million events through state changed helper."""
count = 0
entity_id = 'light.kitchen'
event = asyncio.Event(loop=hass.loop)
@core.callback
def listener(*args):
"""Handle event."""
nonlocal count
count += 1
if count == 10**6:
event.set()
hass.helpers.event.async_track_state_change(
entity_id, listener, 'off', 'on')
event_data = {
'entity_id': entity_id,
'old_state': core.State(entity_id, 'off'),
'new_state': core.State(entity_id, 'on'),
}
for _ in range(10**6):
hass.bus.async_fire(EVENT_STATE_CHANGED, event_data)
start = timer()
yield from event.wait()
return timer() - start