过早优化有时也很有趣
Premature Optimization Is Fun Sometimes

原始链接: https://invlpg.com/posts/2025-06-19-premature-optimization.html

本文通过一个简单的连通性监控系统,探讨了 C 语言结构体优化的细微之处。作者从一个用于存储 Ping 数据的简单 `struct` 开始,通过迭代优化来减小内存占用。 这一过程涉及多个技术难点: 1. **数据精简:** 通过使用标签联合体(tagged union)并降低时间精度(从纳秒降至 100 微秒)来节省空间。 2. **处理填充:** 解决了因内存对齐要求和填充字节导致位域(bitfields)无法减小结构体大小这一常见陷阱。 3. **语义优化:** 用 4 位滚动计数器代替 32 位的 `in_addr_t` 来唯一标识源地址,成功将结构体压缩至单个内存页内。 4. **指令优化:** 通过重新排列位域以确保最佳的 CPU 访问方式(使用 `ldrh` 指令),并运用逻辑翻转技巧(使用 `not_received` 代替 `received`),使编译器能够省略不必要的掩码指令。 尽管作者承认该应用本身并无内存限制,但这一练习突显了对数据布局和编译器行为的深度掌控如何能最小化内存使用并最大化 CPU 效率——这既是出于对性能的追求,也是出于学术性的好奇。

Hacker News 最新 | 往日 | 评论 | 提问 | 展示 | 招聘 | 提交 登录 过早优化有时也很有趣 (invlpg.com) 5 分 | 由 throawayonthe 发布于 1 小时前 | 隐藏 | 往日 | 收藏 | 讨论 | 帮助 准则 | 常见问题 | 列表 | API | 安全 | 法律 | 申请 YC | 联系 搜索:
相关文章

原文
invlpg – Premature Optimization is Fun Sometimes

A colleague of mine was recently discussing a connectivity monitoring system he is working on with me. It’s nothing fancy, just sending ICMP Echo Requests to a couple of different servers, and monitoring latency and dropped packet averages over 1-minute, 5-minute, and 15-minute periods. Up came the topic of how this data should be stored, the natural thought was a 512 entry ring buffer, containing entries like the following:

received bit only requires a shift instruction rather than a shift and a mask:

then the compiler is able to completely elide the mask.

联系我们 contact @ memedata.com