跳到正文
Simon Willison·· 27 天前精选

Willison分享AI编程实验:先跑基准,再针对瓶颈优化

AI 导读

Simon Willison记录用Claude比较C与Rust版SQLite数值解析扩展的过程:先明确输入、异常处理和比较指标,发现初版Rust更快后,再要求优化C版解析函数。作者报告,优化后C版在三类、各200万行测试中,每行净耗时为16至19纳秒。结果限于该实验,不能推广为C全面优于Rust。

推荐理由

提供先测量、再针对瓶颈迭代的AI编程范例,附具体提示词。原文正文+原站 RSS 时间核验;性能数据来自作者实验,未独立复测。

正文 · AI 翻译

研究 将 parse_number() 实现为 SQLite 扩展:C 与 Rust 对比 — 四个 SQLite 扩展分别用 C 和 Rust 实现了相同的 `parse_number()` 行为,测试涵盖类型保留、解析规则和浮点数精度。优化后的 C 实现速度最快,每行耗时 16–19 ns,速度约为 Rust 版本的两倍,且远快于 SQL `replace()`。普通 C 版本由于依赖 `strtod()`,处理小数时速度较慢,而一段简短的快速处理逻辑弥补了这一差距;所有版本在 800 万次模糊测试检查中的结果均一致。

我出门遛狗时,突然好奇:编写一个 SQLite C 扩展,添加一个 parse_number() 函数,将 -$1,234.56 或 '12.5%' 这样的字符串转换为可求和、可排序的数值,究竟有多容易或多困难。

我打开普通的 Claude 聊天(Opus 5.5),输入了以下提示词:

I'm thinking about a SQLite custom function 'parse_number(value)' that strips ',', '$', '£' and '%', handles a leading '-', and returns 'NULL' for anything it can’t parse

Explore the difference between building this as a SQLite extension in C v.s. in Rust - I want to compare performance and code complexity and size of the resulting.so(or whatever) file

这给了我一个扎实的起点:Rust 扩展使用 Rusqlite 时大小为 321 KB,使用 sqlite-loadable-rs 时为 298 KB,而 C 扩展只有 14 KB。但 Rust 扩展运行得更快!

原来,这是因为 Rust 中与 C 的 strtod 对应的实现“速度是其两倍”。于是我输入了以下提示词:

Try writing your own C function for parsing text into a decimal number that catches up to or beats the Rust implementation

它还真做到了:

在 200 万行数据上测得的每行净耗时,越低越好:

初版 C 新版 C rusqlite sqlite-loadable
混合数据 67 ns 19 ns 46 ns 41 ns
仅整数 25 ns 16 ns 36 ns 32 ns
仅小数 106 ns 18 ns 55 ns 47 ns

最后,我让它将原型改写为研究报告,使其风格与 simonw/research 中的其他报告一致,使用的提示词如下:

Clone simonw/research from GitHub and turn your above investigation into a research report as seen in that repository - you can give me a zip file to download that contains your new folder

这是生成的报告。

来源:Simon Willison · simonwillison.net