⚡️ Speed up method Memory.get_total_tokens by 124% in PR #1059 (feat/agentic-codeflash)#1061
Closed
codeflash-ai[bot] wants to merge 1 commit intofeat/agentic-codeflashfrom
Closed
Conversation
The optimized code achieves a **123% speedup** by eliminating function call overhead and avoiding floating-point arithmetic: ## Key Optimizations 1. **Replaced float multiplication with integer division in `encoded_tokens_len`**: - Original: `int(len(s) * 0.25)` performs floating-point multiplication then truncates - Optimized: `len(s) // 4` uses native integer floor division - This is mathematically equivalent for positive integers and avoids the float conversion overhead 2. **Inlined computation in `get_total_tokens` to eliminate function calls**: - Original: Called `encoded_tokens_len()` once per message (4,368 calls in profiler), creating generator overhead plus function call cost - Optimized: Directly computes `len(message["content"]) // 4` in a simple loop - Removes ~4,200 function calls and the `sum()` generator machinery ## Why This Is Faster - **Function call elimination**: Python function calls have significant overhead (stack frame creation, argument passing, return value handling). The line profiler shows the original `encoded_tokens_len` was called 4,368 times at ~429ns per call. The optimized version eliminates most of these calls. - **Float arithmetic avoidance**: Integer operations are faster than float operations in CPUs. The original code performed floating-point multiplication for every message, while the optimized version uses pure integer division. - **Reduced memory allocations**: The generator expression in `sum()` creates an iterator object; the simple loop avoids this allocation. ## Test Results Indicate The optimization benefits **all workloads uniformly**: - Small datasets (empty/single message): 100-140% faster - Medium datasets (50-200 messages): 120-150% faster - Large datasets (500-800 messages): 108-153% faster The speedup is consistent because the optimization reduces per-message overhead proportionally—whether processing 1 message or 1,000, each message benefits equally from eliminated function calls and faster arithmetic. ## Behavior Preservation The mathematical equivalence `int(x * 0.25) == x // 4` for non-negative integers ensures identical results across all test cases, including edge cases with empty strings, Unicode, and large content.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
⚡️ This pull request contains optimizations for PR #1059
If you approve this dependent PR, these changes will be merged into the original PR branch
feat/agentic-codeflash.📄 124% (1.24x) speedup for
Memory.get_total_tokensincodeflash/agent/memory.py⏱️ Runtime :
513 microseconds→229 microseconds(best of250runs)📝 Explanation and details
The optimized code achieves a 123% speedup by eliminating function call overhead and avoiding floating-point arithmetic:
Key Optimizations
Replaced float multiplication with integer division in
encoded_tokens_len:int(len(s) * 0.25)performs floating-point multiplication then truncateslen(s) // 4uses native integer floor divisionInlined computation in
get_total_tokensto eliminate function calls:encoded_tokens_len()once per message (4,368 calls in profiler), creating generator overhead plus function call costlen(message["content"]) // 4in a simple loopsum()generator machineryWhy This Is Faster
encoded_tokens_lenwas called 4,368 times at ~429ns per call. The optimized version eliminates most of these calls.sum()creates an iterator object; the simple loop avoids this allocation.Test Results Indicate
The optimization benefits all workloads uniformly:
The speedup is consistent because the optimization reduces per-message overhead proportionally—whether processing 1 message or 1,000, each message benefits equally from eliminated function calls and faster arithmetic.
Behavior Preservation
The mathematical equivalence
int(x * 0.25) == x // 4for non-negative integers ensures identical results across all test cases, including edge cases with empty strings, Unicode, and large content.✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
🔎 Click to see Concolic Coverage Tests
codeflash_concolic_ik_zub_8/tmpr3v2j3zs/test_concolic_coverage.py::test_Memory_get_total_tokensTo edit these changes
git checkout codeflash/optimize-pr1059-2026-01-15T14.23.38and push.