什么是不同的C ++ math.h abs()相比我的abs() [英] What is different about C++ math.h abs() compared to my abs()

查看:226
本文介绍了什么是不同的C ++ math.h abs()相比我的abs()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在C ++中编写一些类似于glsl的矢量数学类,我只是实现了一个 abs()函数:

I am currently writing some glsl like vector math classes in C++, and I just implemented an abs() function like this:

template<class T>
static inline T abs(T _a)
{
    return _a < 0 ? -_a : _a;
}



我将其速度与默认C ++进行比较 / code>从 math.h 像这样:

clock_t begin = clock();
for(int i=0; i<10000000; ++i)
{
    float a = abs(-1.25);
};

clock_t end = clock();
unsigned long time1 = (unsigned long)((float)(end-begin) / ((float)CLOCKS_PER_SEC/1000.0));

begin = clock();
for(int i=0; i<10000000; ++i)
{
    float a  = myMath::abs(-1.25);
};
end = clock();
unsigned long time2 = (unsigned long)((float)(end-begin) / ((float)CLOCKS_PER_SEC/1000.0));

std::cout<<time1<<std::endl;
std::cout<<time2<<std::endl;

现在默认的abs大约需要25ms,而我的需要60.我想有一些低级优化上。有人知道 math.h abs 如何工作吗?

Now the default abs takes about 25ms while mine takes 60. I guess there is some low level optimisation going on. Does anybody know how math.h abs works internally? The performance difference is nothing dramatic, but I am just curious!

推荐答案

因为他们是实现,他们可以自由地做许多假设,因为他们想要。他们知道 double 的格式,并且可以用它代替。

Since they are the implementation, they are free to make as many assumptions as they want. They know the format of the double and can play tricks with that instead.

可能一个问题),您的 double binary64格式。这意味着符号有自己的位,绝对值只是清除该位。例如,作为专业化,编译器实现者可以执行以下操作

Likely (as in almost not even a question), your double is the binary64 format. This means the sign has it's own bit, and an absolute value is merely clearing that bit. For example, as a specialization, a compiler implementer may do the following:

template <>
double abs<double>(const double x)
{
    // breaks strict aliasing, but compiler writer knows this behavior for the platform
    uint64_t i = reinterpret_cast<const std::uint64_t&>(x);
    i &= 0x7FFFFFFFFFFFFFFFULL; // clear sign bit

    return reinterpret_cast<const double&>(i);
}

这会移除分支,运行更快。

This removes branching and may run faster.

这篇关于什么是不同的C ++ math.h abs()相比我的abs()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆