You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Visual Studio中std::isnan的最优代码生成机制及性能优化方法问询

Visual Studio中std::isnan的最优代码生成机制及性能优化方法问询

大家都知道,检测浮点数是否为NaN(对应标准库的std::isnan)最快的汇编实现方式,是把变量和自身比较——如果结果不相等,就说明这是NaN。而且我观察到GCC和Clang都会为std::isnan生成这类最优的汇编代码。

不过在最新版的Visual Studio里,std::isnan的优化却不是总能生效,我写了一段测试代码就能看出来:

#include <cmath>

bool f( double x, double y ) {
    return std::isnan( x / y );
}

double x, y;

int main() {
    return f( x, y );
}

当用最高级别的速度优化/Ox编译时,函数f确实生成了最优的汇编:

ucomisd xmm0, xmm0
setp    al

但main函数的生成代码就完全不优化了——它没有用ucomisd指令,反而调用了内部函数_dclass,还要对返回值做后续处理:

call    _dclass
xor     ecx, ecx
cmp     ax, 2
sete    cl
mov     eax, ecx

所以我想请教一下,MSVC里到底是什么因素决定了std::isnan是否会被优化成最优的ucomisd实现?有没有什么办法能确保总是生成这种高性能的代码?

备注:内容来源于stack exchange,提问作者Fedor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 17:49:48