Use time.monotonic instead of time.time where appropriate (#31780)

This commit is contained in:
Ville Skyttä 2020-02-13 23:57:07 +02:00 committed by GitHub
parent fbbb29a6ec
commit 3018e8ff47
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 21 additions and 23 deletions

View file

@ -4,7 +4,7 @@ import logging
import logging.handlers import logging.handlers
import os import os
import sys import sys
from time import time from time import monotonic
from typing import Any, Dict, Optional, Set from typing import Any, Dict, Optional, Set
import voluptuous as vol import voluptuous as vol
@ -110,7 +110,7 @@ async def async_from_config_dict(
Dynamically loads required components and its dependencies. Dynamically loads required components and its dependencies.
This method is a coroutine. This method is a coroutine.
""" """
start = time() start = monotonic()
core_config = config.get(core.DOMAIN, {}) core_config = config.get(core.DOMAIN, {})
@ -131,7 +131,7 @@ async def async_from_config_dict(
await _async_set_up_integrations(hass, config) await _async_set_up_integrations(hass, config)
stop = time() stop = monotonic()
_LOGGER.info("Home Assistant initialized in %.2fs", stop - start) _LOGGER.info("Home Assistant initialized in %.2fs", stop - start)
if REQUIRED_NEXT_PYTHON_DATE and sys.version_info[:3] < REQUIRED_NEXT_PYTHON_VER: if REQUIRED_NEXT_PYTHON_DATE and sys.version_info[:3] < REQUIRED_NEXT_PYTHON_VER:

View file

@ -1,7 +1,7 @@
"""Support for BME680 Sensor over SMBus.""" """Support for BME680 Sensor over SMBus."""
import logging import logging
import threading import threading
from time import sleep, time from time import monotonic, sleep
import bme680 # pylint: disable=import-error import bme680 # pylint: disable=import-error
from smbus import SMBus # pylint: disable=import-error from smbus import SMBus # pylint: disable=import-error
@ -240,15 +240,15 @@ class BME680Handler:
# Pause to allow initial data read for device validation. # Pause to allow initial data read for device validation.
sleep(1) sleep(1)
start_time = time() start_time = monotonic()
curr_time = time() curr_time = monotonic()
burn_in_data = [] burn_in_data = []
_LOGGER.info( _LOGGER.info(
"Beginning %d second gas sensor burn in for Air Quality", burn_in_time "Beginning %d second gas sensor burn in for Air Quality", burn_in_time
) )
while curr_time - start_time < burn_in_time: while curr_time - start_time < burn_in_time:
curr_time = time() curr_time = monotonic()
if self._sensor.get_sensor_data() and self._sensor.data.heat_stable: if self._sensor.get_sensor_data() and self._sensor.data.heat_stable:
gas_resistance = self._sensor.data.gas_resistance gas_resistance = self._sensor.data.gas_resistance
burn_in_data.append(gas_resistance) burn_in_data.append(gas_resistance)

View file

@ -285,7 +285,7 @@ class Doods(ImageProcessingEntity):
) )
# Run detection # Run detection
start = time.time() start = time.monotonic()
response = self._doods.detect( response = self._doods.detect(
image, dconfig=self._dconfig, detector_name=self._detector_name image, dconfig=self._dconfig, detector_name=self._detector_name
) )
@ -293,7 +293,7 @@ class Doods(ImageProcessingEntity):
"doods detect: %s response: %s duration: %s", "doods detect: %s response: %s duration: %s",
self._dconfig, self._dconfig,
response, response,
time.time() - start, time.monotonic() - start,
) )
matches = {} matches = {}

View file

@ -90,14 +90,14 @@ class MaxCubeHandle:
self.cube = cube self.cube = cube
self.scan_interval = scan_interval self.scan_interval = scan_interval
self.mutex = Lock() self.mutex = Lock()
self._updatets = time.time() self._updatets = time.monotonic()
def update(self): def update(self):
"""Pull the latest data from the MAX! Cube.""" """Pull the latest data from the MAX! Cube."""
# Acquire mutex to prevent simultaneous update from multiple threads # Acquire mutex to prevent simultaneous update from multiple threads
with self.mutex: with self.mutex:
# Only update every update_interval # Only update every update_interval
if (time.time() - self._updatets) >= self.scan_interval: if (time.monotonic() - self._updatets) >= self.scan_interval:
_LOGGER.debug("Updating") _LOGGER.debug("Updating")
try: try:
@ -106,6 +106,6 @@ class MaxCubeHandle:
_LOGGER.error("Max!Cube connection failed") _LOGGER.error("Max!Cube connection failed")
return False return False
self._updatets = time.time() self._updatets = time.monotonic()
else: else:
_LOGGER.debug("Skipping update") _LOGGER.debug("Skipping update")

View file

@ -1,7 +1,6 @@
"""Support for the Netatmo Weather Service.""" """Support for the Netatmo Weather Service."""
from datetime import timedelta from datetime import timedelta
import logging import logging
from time import time
import pyatmo import pyatmo
@ -519,7 +518,6 @@ class NetatmoData:
"""Initialize the data object.""" """Initialize the data object."""
self.data = {} self.data = {}
self.station_data = station_data self.station_data = station_data
self._next_update = time()
self.auth = auth self.auth = auth
def get_module_infos(self): def get_module_infos(self):

View file

@ -147,12 +147,12 @@ class ProxmoxClient:
verify_ssl=self._verify_ssl, verify_ssl=self._verify_ssl,
) )
self._connection_start_time = time.time() self._connection_start_time = time.monotonic()
def get_api_client(self): def get_api_client(self):
"""Return the ProxmoxAPI client and rebuild it if necessary.""" """Return the ProxmoxAPI client and rebuild it if necessary."""
connection_age = time.time() - self._connection_start_time connection_age = time.monotonic() - self._connection_start_time
# Workaround for the Proxmoxer bug where the connection stops working after some time # Workaround for the Proxmoxer bug where the connection stops working after some time
if connection_age > 30 * 60: if connection_age > 30 * 60:

View file

@ -1,6 +1,6 @@
"""Support for Verisure locks.""" """Support for Verisure locks."""
import logging import logging
from time import sleep, time from time import monotonic, sleep
from homeassistant.components.lock import LockDevice from homeassistant.components.lock import LockDevice
from homeassistant.const import ATTR_CODE, STATE_LOCKED, STATE_UNLOCKED from homeassistant.const import ATTR_CODE, STATE_LOCKED, STATE_UNLOCKED
@ -71,7 +71,7 @@ class VerisureDoorlock(LockDevice):
def update(self): def update(self):
"""Update lock status.""" """Update lock status."""
if time() - self._change_timestamp < 10: if monotonic() - self._change_timestamp < 10:
return return
hub.update_overview() hub.update_overview()
status = hub.get_first( status = hub.get_first(
@ -131,4 +131,4 @@ class VerisureDoorlock(LockDevice):
transaction = hub.session.get_lock_state_transaction(transaction_id) transaction = hub.session.get_lock_state_transaction(transaction_id)
if transaction["result"] == "OK": if transaction["result"] == "OK":
self._state = state self._state = state
self._change_timestamp = time() self._change_timestamp = monotonic()

View file

@ -1,6 +1,6 @@
"""Support for Verisure Smartplugs.""" """Support for Verisure Smartplugs."""
import logging import logging
from time import time from time import monotonic
from homeassistant.components.switch import SwitchDevice from homeassistant.components.switch import SwitchDevice
@ -44,7 +44,7 @@ class VerisureSmartplug(SwitchDevice):
@property @property
def is_on(self): def is_on(self):
"""Return true if on.""" """Return true if on."""
if time() - self._change_timestamp < 10: if monotonic() - self._change_timestamp < 10:
return self._state return self._state
self._state = ( self._state = (
hub.get_first( hub.get_first(
@ -67,13 +67,13 @@ class VerisureSmartplug(SwitchDevice):
"""Set smartplug status on.""" """Set smartplug status on."""
hub.session.set_smartplug_state(self._device_label, True) hub.session.set_smartplug_state(self._device_label, True)
self._state = True self._state = True
self._change_timestamp = time() self._change_timestamp = monotonic()
def turn_off(self, **kwargs): def turn_off(self, **kwargs):
"""Set smartplug status off.""" """Set smartplug status off."""
hub.session.set_smartplug_state(self._device_label, False) hub.session.set_smartplug_state(self._device_label, False)
self._state = False self._state = False
self._change_timestamp = time() self._change_timestamp = monotonic()
# pylint: disable=no-self-use # pylint: disable=no-self-use
def update(self): def update(self):