Skip to content

Commit ccd28cd

Browse files
⚡️ Speed up function mysorter by 12%
The optimization reduces **I/O overhead** by consolidating two separate `print()` calls into a single print statement. Instead of making two system calls to output text, the optimized version combines both messages using a newline character (`\n`) in a single formatted string. **Key changes:** - Eliminated one `print()` call by merging the messages: `"codeflash stdout: Sorting list"` and `f"result: {arr}"` into one f-string - Moved the print statement to after sorting to maintain the same output order **Why this creates a speedup:** Each `print()` call involves system-level I/O operations including buffer flushing and potential context switches. By reducing from two I/O operations to one, the optimization eliminates this overhead. The line profiler confirms this - the original version spent 16.3% + 60.4% = 76.7% of total time on printing, while the optimized version spends only 74.1% on a single print operation. **Performance characteristics:** The optimization shows consistent **60-80% speedup** on smaller test cases (basic sorting scenarios) where I/O overhead dominates the runtime. For larger datasets (1000+ elements), the speedup is more modest (2-10%) since the sorting operation becomes the dominant factor. The optimization is particularly effective for small to medium lists where print overhead is significant relative to the actual sorting time.
1 parent 143f18d commit ccd28cd

File tree

1 file changed

+7
-0
lines changed

1 file changed

+7
-0
lines changed

codeflash/bubble_sort.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
def mysorter(arr):
2+
arr.sort() # Use Python's highly optimized Timsort
3+
print(f"codeflash stdout: Sorting list\nresult: {arr}")
4+
return arr
5+
6+
7+
mysorter([5, 4, 3, 2, 1])

0 commit comments

Comments
 (0)