Google Benchmarks表格中double值末尾出现'm'的解决方法
解决Google Benchmark计数器显示带'm'后缀的问题
问题原因
Google Benchmark的计数器默认会自动对小数值进行缩放并添加单位后缀,这里的'm'代表毫(milli,即10^-3)。比如当命中率为0.005时,会被自动格式化为5m,但直接用cout打印double值时不会触发这种自动缩放逻辑,所以显示正常。
解决方法
有两种常用方案可以避免这种自动格式化:
方案1:禁用计数器的自动缩放
显式指定计数器不进行缩放,保留原始数值的显示格式:
// 替换原来的 state.counters["Hit Ratio"] = hitRatio; state.counters["Hit Ratio"] = benchmark::Counter( hitRatio, benchmark::Counter::kDefaults, benchmark::Counter::kNoScale // 禁用自动缩放 );
你还可以配合kFormatFixed指定固定小数位数,比如保留4位小数:
state.counters["Hit Ratio"] = benchmark::Counter( hitRatio, benchmark::Counter::kFormatFixed, // 固定小数格式 benchmark::Counter::kNoScale );
方案2:转换为百分比显示
将命中率乘以100转换为百分比,这样数值范围变大,不会触发自动缩放,同时结果更直观:
// 替换原来的 state.counters["Hit Ratio"] = hitRatio; state.counters["Hit Ratio (%)"] = benchmark::Counter( hitRatio * 100.0, benchmark::Counter::kDefaults );
代码修改示例
修改后的基准测试函数片段:
double hitRatio = lru_get_hit_ratio(cache); // 使用方案1:禁用缩放+固定小数格式 state.counters["Hit Ratio"] = benchmark::Counter( hitRatio, benchmark::Counter::kFormatFixed, benchmark::Counter::kNoScale ); lru_destroy(cache);
内容的提问来源于stack exchange,提问作者Ajax
相关产品推荐
相关产品推荐

