From a418d49056613c3d0c4ec3b5791566e14f6a313e Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Fri, 29 Aug 2025 00:06:34 +0000 Subject: [PATCH] =?UTF-8?q?=E2=9A=A1=EF=B8=8F=20Speed=20up=20function=20`m?= =?UTF-8?q?anga`=20by=2058%?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The optimized code achieves a **58% speedup** by transforming sequential execution into concurrent execution using `asyncio.gather()` and thread pool execution. **Key optimizations:** 1. **Concurrent execution with `asyncio.gather()`**: Instead of awaiting the API call first, then doing sync work sequentially, both tasks now run concurrently. The async API call (0.3s sleep) overlaps with the sync work (0.5s sleep + computation). 2. **Thread pool execution for blocking operations**: The sync work (`time.sleep()` and `sum()`) is moved to `loop.run_in_executor(None, sync_task)`, which runs it in a separate thread. This prevents blocking the async event loop during the 0.5s sleep and CPU-bound sum calculation. 3. **Parallelism within each iteration**: Each loop iteration now takes ~max(0.3s, 0.5s + computation) = ~0.5s instead of 0.3s + 0.5s + computation = ~0.8s+. **Performance analysis from profiling:** - Original: 99.7% of time spent in blocking `time.sleep(0.5)` calls (30 billion nanoseconds) - Optimized: The blocking operations now run in threads, with the main bottleneck being the executor overhead (65.4% of time in `run_in_executor`) **Best for test cases with:** - Mixed async/sync workloads that can benefit from concurrent execution - Blocking I/O or CPU-bound tasks that can be offloaded to thread pools - Scenarios where the async and sync portions have overlapping execution time The optimization maintains identical behavior and results while dramatically reducing wall-clock time through better concurrency patterns. --- src/async_examples/concurrency.py | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/async_examples/concurrency.py b/src/async_examples/concurrency.py index 7be2352..a9cae28 100644 --- a/src/async_examples/concurrency.py +++ b/src/async_examples/concurrency.py @@ -36,11 +36,17 @@ async def tasker(): async def manga(): results = [] + loop = asyncio.get_running_loop() for i in range(5): - async_result = await fake_api_call(0.3, f"async_{i}") - results.append(async_result) - time.sleep(0.5) - summer = sum(range(100000)) - results.append(f"Sync task {i} completed with sum: {summer}") + def sync_task(): + time.sleep(0.5) + summer = sum(range(100000)) + return f"Sync task {i} completed with sum: {summer}" + + async_result, sync_result = await asyncio.gather( + fake_api_call(0.3, f"async_{i}"), loop.run_in_executor(None, sync_task) + ) + results.append(async_result) + results.append(sync_result) return results