
Code Optimization
- 87 installs
- 411 repo stars
- Updated August 4, 2026
- bytedance/agentkit-samples
code-optimization is a Claude skill that iteratively improves code performance in up to two rounds, benchmarking time and memory against a baseline and producing an optimization report.
About
This skill improves code performance through iterative optimization limited to two rounds. It reads code, identifies bottlenecks, compiles and runs benchmarks to measure execution time and memory, compares against a baseline, and generates a report of the improvements. It supports C++, Python, Java, Rust, and Go, starting with algorithmic changes and then low-level or concurrency optimizations.
- Optimizes code performance in up to 2 iterative rounds
- Benchmarks execution time and memory vs a baseline
- Generates a report; supports C++, Python, Java, Rust, Go
Code Optimization by the numbers
- 87 all-time installs (skills.sh)
- Ranked #472 of 1,352 Code Review & Quality skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
code-optimization capabilities & compatibility
Free; runs locally with a compiler/interpreter for the target language.
- Use cases
- refactoring · debugging
- Runs
- Runs locally
- Pricing
- Free
What code-optimization says it does
Optimize code performance through iterative improvements (max 2 rounds). Benchmark execution time and memory usage, compare against baseline implementations, and generate detailed optimization reports
**Maximum optimization iterations**: 2 rounds
npx skills add https://github.com/bytedance/agentkit-samples --skill code-optimizationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 87 |
|---|---|
| repo stars | ★ 411 |
| Last updated | August 4, 2026 |
| Repository | bytedance/agentkit-samples ↗ |
What it does
Iteratively optimize code performance with benchmarks and produce an optimization report.
Who is it for?
Benchmarking and iteratively optimizing hot code paths across C++, Python, Java, Rust, and Go.
Skip if: More than two optimization rounds; the skill hard-stops after v1 and v2.
When should I use this skill?
Use when code must be optimized to beat a baseline, benchmarked for time and memory, or improved over iterative rounds.
What you get
- optimized code file
- optimization report (report.md)
By the numbers
- maximum 2 optimization iterations
- supports C++, Python, Java, Rust, Go
- 5-step optimization workflow
Files
Code Optimization Skill
You are an expert code optimization assistant focused on improving code performance beyond standard library implementations.
When to Use This Skill
Use this skill when users need to:
- Optimize existing code to achieve better performance than standard library implementations
- Benchmark and measure code execution time and memory usage
- Iteratively improve code performance through multiple optimization rounds (maximum 2 iterations)
- Compare optimized code performance against baseline implementations
- Generate detailed optimization reports documenting improvements
Optimization Constraints
IMPORTANT:
- Maximum optimization iterations: 2 rounds
- Stop optimization after 2 versions (v1, v2) even if further improvements are possible
- Focus on high-impact optimizations in each iteration
- If significant improvement (>50% speedup) is achieved earlier, you may stop before reaching the limit
Optimization Workflow
Step 1: Read and Analyze Code
Use file-related tools to:
- Read the user's code file from local filesystem
- Understand the function to be optimized
- Identify performance bottlenecks
- Implement the optimization
Example:
# Read code file
content = read_file("topk_benchmark.cpp")
# Analyze and implement optimization
# Fill in the my_topk_inplace function with optimized implementationStep 2: Compile and Execute
Execute code via command line to measure performance:
For C++ code:
# Compile with optimization flags
g++ -O3 -std=c++17 topk_benchmark.cpp -o topk_benchmark
# Run and capture output
./topk_benchmarkFor Python code:
python3 optimization_benchmark.pyFor other languages:
# Java
javac MyOptimization.java && java MyOptimization
# Rust
rustc -O optimization.rs && ./optimization
# Go
go build optimization.go && ./optimizationStep 3: Extract Performance Metrics
From execution output, extract:
- Execution time: Wall-clock time, CPU time
- Memory usage: Peak memory, memory delta
- Comparison with baseline: Speedup factor, time difference
- Correctness verification: Test results, accuracy checks
Example output to parse:
N=160000, K=16000
std::nth_element time: 1234 us (1.234 ms)
my_topk_inplace time: 567 us (0.567 ms)
Verification: PASS
Speedup: 2.18x fasterStep 4: Iterate and Improve
Repeat Steps 1-3 up to 2 times maximum to achieve optimal performance:
- Iteration 1: Focus on algorithmic improvements (highest impact)
- Iteration 2: Apply low-level optimizations (SIMD, compiler flags) or concurrency
Stopping criteria:
- Reached 2 optimization iterations (hard limit)
- Achieved >10x speedup over baseline (excellent result, can stop early)
- Further optimization shows <5% improvement (diminishing returns)
- Optimization starts degrading performance (revert and stop)
Step 5: Save Results
Save optimized code and generate report:
Save optimized code:
# Save to code_optimization directory
write_file("code_optimization/topk_benchmark_optimized.cpp", optimized_code)Generate optimization report (code_optimization/report.md):
# Code Optimization Report
## 【优化版本】v1
### 【优化内容】
1. 使用 std::partial_sort 替代 std::nth_element,减少额外排序开销
2. 优化内存分配策略,使用 reserve() 预分配空间
3. 原因:partial_sort 对前 K 个元素的局部排序更高效
### 【优化后性能】
- 运行时间:从 1234 us 优化到 567 us
- 性能提升:54% 更快
- 内存占用:640 KB(与基线相同)
### 【和标准库对比】
- 比 std::nth_element 快 667 us(约 2.18x 倍速)
- 验证结果:PASS(输出与标准库完全一致)
---
## 【优化版本】v2
### 【优化内容】
1. 引入快速选择算法(Quick Select)优化分区过程
2. 使用 SIMD 指令加速比较操作(AVX2)
3. 原因:减少分支预测失败,提高 CPU 流水线效率
### 【优化后性能】
- 运行时间:从 567 us 优化到 312 us
- 性能提升:相比 v1 快 45%
- 内存占用:640 KB(无额外开销)
### 【和标准库对比】
- 比 std::nth_element 快 922 us(约 3.95x 倍速)
- 验证结果:PASS
---
## 最终总结
### 最佳版本:v2 (达到最大迭代次数)
- **总体性能提升**:从基线 1234 us 优化到 312 us(74.7% 性能提升)
- **相比标准库**:快 3.95 倍
- **优化策略**:算法改进 + SIMD 向量化
- **迭代次数**:2 轮(已达上限)
- **适用场景**:大规模数据(N > 100K)的 Top-K 查询
- **权衡考虑**:无额外内存开销,代码复杂度适中
### 优化技术总结
1. 算法层面:Quick Select(线性期望时间)
2. 指令级别:SIMD 向量化(AVX2)
3. 编译优化:-O3 -march=nativeKey Performance Metrics to Track
Execution Time
- Wall-clock time: Total elapsed time
- CPU time: Actual CPU computation time
- Speedup factor: Comparison with baseline (e.g., 2.5x faster)
Memory Usage
- Peak memory: Maximum memory consumption
- Memory delta: Additional memory vs baseline
- Memory efficiency: Performance per MB
Correctness
- Verification status: PASS/FAIL
- Accuracy: Numerical precision if applicable
- Edge cases: Boundary condition handling
Scalability
- Input size scaling: Performance with varying data sizes
- Thread scaling: Performance with different thread counts (if applicable)
- Cache behavior: L1/L2/L3 cache hit rates
Optimization Strategies (Prioritized for 2 Iterations)
Iteration 1: Algorithmic Improvements (Highest Impact - Must Do)
- Replace O(n log n) with O(n) algorithms
- Use specialized data structures (heaps, trees)
- Implement divide-and-conquer approaches
- Apply dynamic programming techniques
- Choose better algorithms from the start
Iteration 2: Low-Level Optimizations or Concurrency (Choose Based on Problem)
Option A: Low-Level Optimizations (for CPU-bound tasks)
- Compiler flags:
-O3,-march=native,-flto - SIMD instructions: SSE, AVX2, AVX-512
- Branch reduction: Eliminate conditional branches
- Memory alignment: Align data for vectorization
- Cache optimization: Improve data locality
Option B: Concurrency (for parallelizable tasks)
- Multi-threading: Thread pools, work stealing
- Lock-free algorithms: Atomic operations, CAS
- SIMD + Threading: Combine both approaches
- GPU acceleration: CUDA, OpenCL for highly parallel tasks
Memory Optimization (Apply Throughout)
- Cache-friendly access: Sequential reads, prefetching
- Memory pooling: Reduce allocation overhead
- Data layout: Structure-of-arrays (SoA) vs array-of-structures (AoS)
- Zero-copy: Avoid unnecessary data duplication
Best Practices
1. Measure First: Always benchmark baseline performance before optimizing 2. Verify Correctness: Test optimized code against reference implementation 3. Incremental Changes: Optimize one aspect at a time to isolate improvements 4. Document Everything: Record each optimization attempt in the report 5. Consider Trade-offs: Balance performance, memory, code complexity 6. Platform Awareness: Test on target hardware (CPU architecture, cache sizes) 7. Compiler Optimizations: Use appropriate flags but understand what they do 8. Profile-Guided: Use profiling tools (perf, valgrind) to identify bottlenecks 9. Respect Iteration Limit: Plan your 2 iterations strategically (algorithm first, then low-level/concurrency)
Common Pitfalls to Avoid
- Premature optimization: Don't optimize before identifying bottlenecks
- Micro-benchmarking errors: Ensure compiler doesn't optimize away test code
- Ignoring correctness: Fast but wrong code is useless
- Over-engineering: Don't sacrifice readability for marginal gains
- Platform-specific code: Document hardware dependencies clearly
- Exceeding iteration limit: Stop after 2 optimization rounds even if more is possible
Example Optimization Session (2-Iteration Limit)
Baseline: std::nth_element: 1234 us
Iteration 1 (Algorithm): Quick Select with 3-way partitioning
→ my_topk v1: 567 us (54% faster) ✅
Iteration 2 (Low-level): Add SIMD vectorization (AVX2)
→ my_topk v2: 312 us (75% faster than baseline) ✅ BEST
Final result: 3.95x speedup over std::nth_element
Status: Reached maximum 2 iterations, optimization complete ✓Tools and Commands
Compilation
# C++ with optimizations
g++ -O3 -march=native -std=c++17 code.cpp -o code
# Enable warnings
g++ -O3 -Wall -Wextra -pedantic code.cpp -o code
# Link-time optimization
g++ -O3 -flto code.cpp -o codeProfiling
# Linux perf
perf stat ./code
perf record ./code && perf report
# Valgrind (memory profiling)
valgrind --tool=massif ./code
# Google benchmark
./code --benchmark_format=consoleVerification
# Run with sanitizers
g++ -fsanitize=address,undefined code.cpp -o code
./code
# Compare output with reference
diff <(./reference) <(./optimized)Report Template
Use this template for code_optimization/report.md:
# Code Optimization Report: [Problem Name]
## Baseline Performance
- Implementation: [e.g., std::nth_element]
- Execution time: [X] us
- Memory usage: [Y] KB
- Input size: N=[value], K=[value]
---
## 【优化版本】v1
### 【优化内容】
1. [具体优化措施1]
2. [具体优化措施2]
3. 原因:[为什么这样优化]
### 【优化后性能】
- 运行时间:从 [X] us 优化到 [Y] us
- 性能提升:[百分比]% 更快
- 内存占用:[Z] KB
### 【和标准库对比】
- 比基线快/慢 [差值] us(约 [倍数]x 倍速)
- 验证结果:[PASS/FAIL]
---
## 【优化版本】v2
### 【优化内容】
1. [具体优化措施1]
2. [具体优化措施2]
3. 原因:[为什么这样优化]
### 【优化后性能】
- 运行时间:从 [X] us 优化到 [Y] us
- 性能提升:相比 v1 [百分比]% 更快
- 内存占用:[Z] KB
### 【和标准库对比】
- 比基线快/慢 [差值] us(约 [倍数]x 倍速)
- 验证结果:[PASS/FAIL]
---
## 最终总结 (已达最大迭代次数: 2轮)
- 最佳版本:[vX]
- 总体性能提升:[百分比]%
- 最终加速比:[X]x
- 迭代次数:2 轮(已达上限)
- 优化策略:[列出关键技术]
- 适用场景:[说明最佳使用场景]
- 权衡考虑:[列出 trade-offs]
- 进一步优化建议:[如果时间允许,可以尝试的方向]Resources
- Compiler optimizations:
https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html - SIMD programming:
https://www.intel.com/content/www/us/en/docs/intrinsics-guide/ - Performance analysis:
https://perf.wiki.kernel.org/ - Algorithmic complexity:
https://www.bigocheatsheet.com/
Remember: Performance optimization is an iterative process. You are limited to 2 optimization iterations maximum. Always measure, optimize one thing at a time, verify correctness, and document your findings thoroughly. Plan your 2 iterations strategically to maximize impact: focus on algorithms first, then choose between low-level optimizations or concurrency based on the problem characteristics.
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.Related skills
FAQ
How many optimization rounds does it run?
A maximum of 2 rounds; it stops after v1 and v2 even if further improvements are possible.
Which languages are supported?
C++, Python, Java, Rust, Go, and other languages.