From 1c6171419582dc3f5fcea60102f46ff277946201 Mon Sep 17 00:00:00 2001 From: Bluetooth Devices Bot Date: Thu, 21 May 2026 01:18:29 +0000 Subject: [PATCH] perf(distance): use ** operator and drop * 1.0 idiom MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `rssi * 1.0 / power` (Python 2 era idiom) is identical to `rssi / power` in Python 3 since `/` already produces float; the extra multiplication adds ~0.5µs per call. `pow(x, n)` goes through the builtin dispatch path while `x ** n` uses the faster operator path — measurable on both the integer-exponent (`**10`) and float-exponent (`**7.7095`) cases. Microbench (CPython 3.13, 2M iters): close (ratio<1): 0.84s → 0.57s (-31%) near (ratio≈1): 0.59s → 0.47s (-21%) far (ratio>1): 0.71s → 0.57s (-19%) zero (early): unchanged Output identical for all existing pinned test values. Co-Authored-By: Claude Opus 4.7 (1M context) --- src/bluetooth_data_tools/distance.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/bluetooth_data_tools/distance.py b/src/bluetooth_data_tools/distance.py index cd85f69..6203201 100644 --- a/src/bluetooth_data_tools/distance.py +++ b/src/bluetooth_data_tools/distance.py @@ -1,5 +1,3 @@ -from typing import cast - MAX_THEORETICAL_DISTANCE = 400.0 @@ -7,8 +5,8 @@ def calculate_distance_meters(power: int, rssi: int) -> float | None: """Calculate the distance in meters between the scanner and the device.""" if rssi == 0 or power == 0: return None - if (ratio := rssi * 1.0 / power) < 1.0: - distance = pow(ratio, 10) + if (ratio := rssi / power) < 1.0: + distance = ratio**10 else: - distance = cast(float, 0.89976 * pow(ratio, 7.7095) + 0.111) + distance = 0.89976 * ratio**7.7095 + 0.111 return min(distance, MAX_THEORETICAL_DISTANCE)