File: profile_init.py

package info (click to toggle)
python-bsblan 4.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,196 kB
  • sloc: python: 6,864; makefile: 3
file content (422 lines) | stat: -rw-r--r-- 12,998 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
"""Profile BSBLAN initialization to identify performance bottlenecks.

This script profiles the initialization process of the BSBLAN library
to help identify slow operations that affect Home Assistant startup time.

Usage:
    # Basic profiling with auto-discovery or BSBLAN_HOST env var
    uv run python examples/profile_init.py

    # With explicit host
    uv run python examples/profile_init.py --host YOUR_BSBLAN_IP

    # With cProfile output
    uv run python examples/profile_init.py --cprofile

    # Save cProfile stats to file for analysis
    uv run python examples/profile_init.py --cprofile --output stats.prof
"""

from __future__ import annotations

import argparse
import asyncio
import cProfile
import pstats
import sys
import time
from contextlib import asynccontextmanager
from pathlib import Path
from typing import TYPE_CHECKING, Any

import aiohttp

if TYPE_CHECKING:
    from collections.abc import AsyncIterator

# Add src to path for development
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))

from bsblan import BSBLAN, BSBLANConfig
from bsblan.exceptions import BSBLANError
from bsblan.utility import APIValidator
from discovery import get_bsblan_host, get_config_from_env


class TimingStats:
    """Collect timing statistics for operations."""

    def __init__(self) -> None:
        """Initialize timing stats."""
        self.timings: dict[str, float] = {}
        self.start_times: dict[str, float] = {}

    def start(self, name: str) -> None:
        """Start timing an operation."""
        self.start_times[name] = time.perf_counter()

    def stop(self, name: str) -> float:
        """Stop timing and return elapsed time."""
        elapsed = time.perf_counter() - self.start_times[name]
        self.timings[name] = elapsed
        return elapsed

    @asynccontextmanager
    async def measure(self, name: str) -> AsyncIterator[None]:
        """Context manager to measure async operation time."""
        self.start(name)
        try:
            yield
        finally:
            self.stop(name)

    def report(self) -> str:
        """Generate a timing report."""
        lines = [
            "",
            "=" * 60,
            "TIMING BREAKDOWN",
            "=" * 60,
        ]

        total = sum(self.timings.values())

        # Sort by duration, longest first
        sorted_timings = sorted(self.timings.items(), key=lambda x: x[1], reverse=True)

        for name, duration in sorted_timings:
            pct = (duration / total * 100) if total > 0 else 0
            bar = "█" * int(pct / 2)
            lines.append(f"{name:40} {duration:8.3f}s ({pct:5.1f}%) {bar}")

        lines.extend(
            [
                "-" * 60,
                f"{'TOTAL':40} {total:8.3f}s",
                "=" * 60,
            ]
        )

        return "\n".join(lines)


async def profile_detailed(
    config: BSBLANConfig,
) -> tuple[BSBLAN, TimingStats]:
    """Profile initialization with detailed timing of each step.

    This profiles the NEW lazy loading approach where sections are
    validated on-demand when first accessed.

    Note: Caller is responsible for closing client.session on success.
    """
    stats = TimingStats()

    async with stats.measure("1. Create aiohttp session"):
        session = aiohttp.ClientSession()

    client = BSBLAN(config=config, session=session)
    success = False

    try:
        # Profile lazy loading initialization (minimal upfront work)
        # Access private methods for profiling (pylint: disable=protected-access)
        async with stats.measure("2. Initialize (lazy - firmware only)"):
            # This now only fetches firmware + sets up validator
            await client.initialize()

        # Now profile what happens when we actually use sections
        # This is where lazy loading kicks in
        async with stats.measure("3. First state() call (triggers heating validation)"):
            await client.state()

        async with stats.measure("4. First sensor() call (triggers sensor validation)"):
            await client.sensor()

        async with stats.measure("5. First static_values() (triggers staticValues)"):
            await client.static_values()

        async with stats.measure("6. First hot_water_state() (triggers hot_water)"):
            await client.hot_water_state()

        success = True
        return client, stats

    finally:
        if not success:
            await session.close()


async def profile_hot_water_granular(config: BSBLANConfig) -> TimingStats:
    """Profile granular hot water parameter loading.

    This shows the benefit of only loading specific parameter groups
    (essential: 5 params, config: 16 params, schedule: 8 params)
    instead of all 29 hot water parameters at once.
    """
    stats = TimingStats()

    async with stats.measure("Create session"):
        session = aiohttp.ClientSession()

    try:
        client = BSBLAN(config=config, session=session)

        # Initialize (lazy - firmware only)
        async with stats.measure("Initialize (lazy)"):
            await client.initialize()

        # Profile each hot water method - each validates only its param group
        async with stats.measure("hot_water_state (5 essential params)"):
            await client.hot_water_state()

        async with stats.measure("hot_water_config (16 config params)"):
            await client.hot_water_config()

        async with stats.measure("hot_water_schedule (8 schedule params)"):
            await client.hot_water_schedule()

        # Second calls should be instant (already validated)
        async with stats.measure("hot_water_state (cached - no validation)"):
            await client.hot_water_state()

    finally:
        await session.close()

    return stats


async def profile_sections(config: BSBLANConfig) -> TimingStats:
    """Profile each section validation individually."""
    stats = TimingStats()

    async with stats.measure("Create session"):
        session = aiohttp.ClientSession()

    try:
        client = BSBLAN(config=config, session=session)

        # Get firmware version first (pylint: disable=protected-access)
        async with stats.measure("Fetch firmware version"):
            await client._fetch_firmware_version()  # noqa: SLF001

        # Initialize API data before validation
        client._api_data = client._copy_api_config()  # noqa: SLF001
        client._api_validator = APIValidator(client._api_data)  # noqa: SLF001

        # Profile each section individually
        sections = ["heating", "sensor", "staticValues", "device", "hot_water"]
        for section in sections:
            async with stats.measure(f"Validate section: {section}"):
                try:
                    await client._validate_api_section(section)  # type: ignore[arg-type]  # noqa: SLF001
                except BSBLANError as err:
                    print(f"Warning: Section {section} validation failed: {err}")

    finally:
        await session.close()

    return stats


async def profile_standard(config: BSBLANConfig) -> tuple[float, BSBLAN]:
    """Profile standard initialization using context manager."""
    start = time.perf_counter()

    client = BSBLAN(config=config)
    await client.__aenter__()

    elapsed = time.perf_counter() - start
    return elapsed, client


def run_cprofile(config: BSBLANConfig) -> tuple[pstats.Stats, float]:
    """Run cProfile on the initialization."""
    profiler = cProfile.Profile()

    async def _init() -> tuple[float, Any]:
        return await profile_standard(config)

    profiler.enable()
    elapsed, client = asyncio.run(_init())
    profiler.disable()

    # Cleanup
    asyncio.run(client.__aexit__(None, None, None))

    stats = pstats.Stats(profiler)
    return stats, elapsed


def parse_args() -> argparse.Namespace:
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(
        description="Profile BSBLAN initialization performance"
    )
    parser.add_argument(
        "--host",
        help="BSBLAN device IP (uses BSBLAN_HOST env or mDNS discovery if not set)",
    )
    parser.add_argument("--port", type=int, default=80, help="BSBLAN device port")
    parser.add_argument("--username", help="Username for authentication")
    parser.add_argument("--password", help="Password for authentication")
    parser.add_argument("--passkey", help="Passkey for authentication")
    parser.add_argument(
        "--cprofile", action="store_true", help="Enable cProfile output"
    )
    parser.add_argument(
        "--output", help="Save cProfile stats to file (use with --cprofile)"
    )
    parser.add_argument(
        "--sections",
        action="store_true",
        help="Profile each section validation individually",
    )
    parser.add_argument(
        "--hot-water",
        action="store_true",
        help="Profile granular hot water parameter loading",
    )
    parser.add_argument(
        "--repeat",
        type=int,
        default=1,
        help="Number of times to repeat profiling (for averaging)",
    )
    return parser.parse_args()


def run_cprofile_mode(config: BSBLANConfig, output: str | None) -> None:
    """Run cProfile mode."""
    print("\nRunning with cProfile...")
    stats, elapsed = run_cprofile(config)

    print(f"\nTotal initialization time: {elapsed:.3f}s")
    print("\n" + "=" * 60)
    print("cProfile Results (top 30 by cumulative time):")
    print("=" * 60)

    # Print stats to stdout
    stats.sort_stats("cumulative")
    stats.print_stats(30)

    if output:
        stats.dump_stats(output)
        print(f"\nStats saved to: {output}")
        print(f"Analyze with: python -m pstats {output}")


async def run_sections_mode(config: BSBLANConfig) -> None:
    """Run sections profiling mode."""
    print("\nProfiling individual section validations...")
    stats = await profile_sections(config)
    print(stats.report())


async def run_detailed_mode(config: BSBLANConfig, repeat: int) -> None:
    """Run detailed timing mode."""
    print("\nRunning detailed timing analysis...")
    times: list[float] = []

    for i in range(repeat):
        if repeat > 1:
            print(f"\nRun {i + 1}/{repeat}")

        client, stats = await profile_detailed(config)
        times.append(sum(stats.timings.values()))

        print(stats.report())

        # Cleanup
        if client.session:
            await client.session.close()

    if repeat > 1:
        avg = sum(times) / len(times)
        min_t = min(times)
        max_t = max(times)
        print("\n" + "=" * 60)
        print("SUMMARY ACROSS RUNS")
        print("=" * 60)
        print(f"Average: {avg:.3f}s")
        print(f"Min:     {min_t:.3f}s")
        print(f"Max:     {max_t:.3f}s")


def print_recommendations() -> None:
    """Print optimization recommendations."""
    print("\n" + "=" * 60)
    print("RECOMMENDATIONS")
    print("=" * 60)
    print("""
If network requests are slow:
- Check network latency to your BSB-LAN device
- Consider if some validation can be cached/skipped

If section validation is slow:
- The library validates 5 sections sequentially
- Each section requires a network round-trip
- Consider parallel validation or lazy loading

For Home Assistant specifically:
- The integration may benefit from caching device info
- Consider using config entry caching for static data
""")


async def run_hot_water_mode(config: BSBLANConfig) -> None:
    """Run hot water granular profiling mode."""
    print("\nProfiling granular hot water parameter loading...")
    print("This shows the benefit of only loading specific param groups.\n")

    stats = await profile_hot_water_granular(config)
    print(stats.report())


async def async_main() -> None:
    """Async main for profiling."""
    args = parse_args()

    # Get host from args, env, or discovery
    if args.host:
        host = args.host
        port = args.port
    else:
        host, port = await get_bsblan_host()

    # Get credentials from args or env
    env_config = get_config_from_env()
    username = args.username or env_config.get("username")
    password = args.password or env_config.get("password")
    passkey = args.passkey or env_config.get("passkey")

    config = BSBLANConfig(
        host=host,
        port=port,
        username=username,  # type: ignore[arg-type]
        password=password,  # type: ignore[arg-type]
        passkey=passkey,  # type: ignore[arg-type]
    )

    print(f"Profiling BSBLAN initialization for {host}:{port}")
    print("=" * 60)

    if args.cprofile:
        run_cprofile_mode(config, args.output)
    elif args.sections:
        await run_sections_mode(config)
    elif args.hot_water:
        await run_hot_water_mode(config)
    else:
        await run_detailed_mode(config, args.repeat)

    print_recommendations()


def main() -> None:
    """Run profiling with command line arguments."""
    asyncio.run(async_main())


if __name__ == "__main__":
    main()