From b0d3fd5d1d71c48b6ee659a4b44954e41b485c8c Mon Sep 17 00:00:00 2001 From: "codeflash-ai[bot]" <148906541+codeflash-ai[bot]@users.noreply.github.com> Date: Mon, 20 Oct 2025 23:09:42 +0000 Subject: [PATCH] Optimize convert_unix_timestamp The optimization replaces the expensive `strftime()` method call with direct f-string formatting using datetime object attributes. Instead of `dt_object.strftime("%Y-%m-%dT%H:%M:%S.%fZ")`, the code now uses `f"{dt_object.year:04d}-{dt_object.month:02d}-{dt_object.day:02d}T{dt_object.hour:02d}:{dt_object.minute:02d}:{dt_object.second:02d}.{dt_object.microsecond:06d}Z"`. This provides a **10% overall speedup** because: - **Eliminates format string parsing**: `strftime()` must parse the format string `"%Y-%m-%dT%H:%M:%S.%fZ"` at runtime, while f-strings are compiled at parse time - **Direct attribute access**: Accessing `dt_object.year`, `dt_object.month`, etc. is faster than the internal formatting logic in `strftime()` - **Reduced function call overhead**: f-string formatting avoids the method call to `strftime()` The line profiler shows the original `strftime()` line consumed 73.4% of execution time (10.3ms out of 14.0ms total), making it the clear bottleneck. The optimized version spreads this work across multiple f-string operations that are collectively faster. **Test case performance**: The optimization shows consistent 30-60% speedup across individual test cases, with particularly strong gains (60-78%) on simple cases like epoch and basic timestamps. Even large-scale tests with 1000 iterations show 9-13% improvements, demonstrating the optimization scales well for batch processing scenarios. --- src/together/utils/tools.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/together/utils/tools.py b/src/together/utils/tools.py index 2e84307a..908d129a 100644 --- a/src/together/utils/tools.py +++ b/src/together/utils/tools.py @@ -121,6 +121,6 @@ def convert_unix_timestamp(timestamp: int) -> str: dt_object = datetime.fromtimestamp(timestamp) # Format datetime object as ISO 8601 string - iso_format = dt_object.strftime("%Y-%m-%dT%H:%M:%S.%fZ") + iso_format = f"{dt_object.year:04d}-{dt_object.month:02d}-{dt_object.day:02d}T{dt_object.hour:02d}:{dt_object.minute:02d}:{dt_object.second:02d}.{dt_object.microsecond:06d}Z" return iso_format