Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

⚡️ Speed up methodUsage.opentelemetry_attributes by 85%#2198

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Conversation

misrasaurabh1
Copy link
Contributor

📄 85% (0.85x) speedup forUsage.opentelemetry_attributes inpydantic_ai_slim/pydantic_ai/usage.py

⏱️ Runtime :2.09 milliseconds1.13 milliseconds (best of77 runs)

📝 Explanation and details

Here is the optimized version of your program for maximal runtime efficiency and reduced memory allocations, especially for the bottleneck section.

Performance improvements:

  • Avoided unconditional allocation and population of dictionary keys with possibly falsy values, which were later filtered out at return. This eliminates the need to create then filter unnecessary key-value pairs, and the dict comprehension at the end.
  • Reuses the string prefix instead of f-strings in the tight loop for minor efficiency improvement.
  • Now we only touch details if it's not None (no allocation of empty dict).
  • No post-process dict comprehension; only desired keys added directly.

The function returns exactly the same result as the original, but avoids unnecessary work and memory churn.

Correctness verification report:

TestStatus
⚙️ Existing Unit Tests🔘None Found
🌀 Generated Regression Tests2004 Passed
⏪ Replay Tests243 Passed
🔎 Concolic Coverage Tests🔘None Found
📊 Tests Coverage100.0%
🌀 Generated Regression Tests and Runtime
fromcollectionsimportnamedtuple# function to testfromcopyimportcopyfromdataclassesimportdataclassfromtypingimportOptional# importsimportpytest# used for our unit testsfrompydantic_ai.usageimportUsage# Dummy _utils for repr to avoid import errorclass_utils:@staticmethoddefdataclasses_no_defaults_repr(self):returnf"Usage(requests={self.requests}, request_tokens={self.request_tokens}, response_tokens={self.response_tokens}, total_tokens={self.total_tokens}, details={self.details})"frompydantic_ai.usageimportUsage# unit tests# Basic Test Casesdeftest_empty_usage():# All fields are None or 0, should return empty dictusage=Usage()codeflash_output=usage.opentelemetry_attributes();attrs=codeflash_output# 1.76μs -> 668ns (163% faster)# Edge Test Casesfromcopyimportcopyfromdataclassesimportdataclass# importsimportpytest# used for our unit testsfrompydantic_ai.usageimportUsage# Dummy _utils for repr to avoid dependency on pydantic_ai._utilsclass_utils:@staticmethoddefdataclasses_no_defaults_repr(self):returnf"Usage({self.requests},{self.request_tokens},{self.response_tokens},{self.total_tokens},{self.details})"frompydantic_ai.usageimportUsage# unit tests# 1. Basic Test Casesdeftest_edge_all_none():# All fields None or defaultusage=Usage()codeflash_output=usage.opentelemetry_attributes();attrs=codeflash_output# 1.73μs -> 614ns (181% faster)deftest_large_scale_tokens_and_details_none():# All fields None, large number of Usage objectsusages= [Usage()for_inrange(1000)]forusageinusages:codeflash_output=usage.opentelemetry_attributes()# 417μs -> 178μs (134% faster)frompydantic_ai.usageimportUsagedeftest_Usage_opentelemetry_attributes():Usage.opentelemetry_attributes(Usage(requests=0,request_tokens=None,response_tokens=None,total_tokens=None,details={'':-1}))deftest_Usage_opentelemetry_attributes_2():Usage.opentelemetry_attributes(Usage(requests=0,request_tokens=None,response_tokens=0,total_tokens=None,details=None))
⏪ Replay Tests and Runtime
Test File::Test FunctionOriginal ⏱️Optimized ⏱️Speedup
codeflash_concolic_t7q2nx26/tmpwofuw3vl/test_concolic_coverage.py::test_Usage_opentelemetry_attributes2.32μs1.41μs✅65.2%
codeflash_concolic_t7q2nx26/tmpwofuw3vl/test_concolic_coverage.py::test_Usage_opentelemetry_attributes_21.81μs691ns✅163%
test_pytest_inlinesnapshotdisable_testsproviderstest_bedrock_py_testsproviderstest_google_gla_py_teststes__replay_test_0.py::test_pydantic_ai_usage_Usage_opentelemetry_attributes138μs82.8μs✅67.6%
test_pytest_inlinesnapshotdisable_teststest_messages_py_teststest_mcp_py_teststest_deps_py__replay_test_0.py::test_pydantic_ai_usage_Usage_opentelemetry_attributes9.00μs4.72μs✅90.4%

To edit these changesgit checkout codeflash/optimize-Usage.opentelemetry_attributes-md0bn5hj and push.

Codeflash

codeflash-aibotand others added3 commitsJuly 12, 2025 14:08
Here is the optimized version of your program for maximal runtime efficiency and reduced memory allocations, especially for the bottleneck section.**Performance improvements:**- Avoided unconditional allocation and population of dictionary keys with possibly falsy values, which were later filtered out at return. This eliminates the need to create then filter unnecessary key-value pairs, and the dict comprehension at the end.- Reuses the string prefix instead of f-strings in the tight loop for minor efficiency improvement.- Now we only touch details if it's not None (no allocation of empty dict).- No post-process dict comprehension; only desired keys added directly.The function returns exactly the same result as the original, but avoids unnecessary work and memory churn.
@DouweMDouweM merged commit8f63ba3 intopydantic:mainJul 17, 2025
18 checks passed
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Reviewers
No reviews
Assignees
No one assigned
Labels
None yet
Projects
None yet
Milestone
No milestone
Development

Successfully merging this pull request may close these issues.

2 participants
@misrasaurabh1@DouweM

[8]ページ先頭

©2009-2025 Movatter.jp