cvCeil()是否比标准库快?

问题描述 投票:0回答:1

我看到OpenCV实现了cvCeil功能:

CV_INLINE  int  cvCeil( double value )
{
#if defined _MSC_VER && defined _M_X64 || (defined __GNUC__ && defined __SSE2__&& !defined __APPLE__)
    __m128d t = _mm_set_sd( value );
    int i = _mm_cvtsd_si32(t);
    return i + _mm_movemask_pd(_mm_cmplt_sd(_mm_cvtsi32_sd(t,i), t));
#elif defined __GNUC__
    int i = (int)value;
    return i + (i < value);
#else
    int i = cvRound(value);
    float diff = (float)(i - value);
    return i + (diff < 0);
#endif
}

我对此实现的第一部分很好奇,即与_mm_set_sd相关的调用。它们会比MSVCRT / libstdc ++ / libc ++快吗?为什么?

c++ optimization c++-standard-library
1个回答
0
投票

下面的一个简单基准测试告诉我,std::round在启用SSE4的计算机上的运行速度提高了3倍,但在未启用AVX的情况下,运行速度降低了约2倍。

#include <cmath>
#include <chrono>
#include <sstream>
#include <iostream>
#include <opencv2/core/fast_math.hpp>

auto currentTime() { return std::chrono::steady_clock::now(); }

template<typename T, typename P>
std::string toString(std::chrono::duration<T,P> dt)
{
    std::ostringstream str;
    using namespace std::chrono;
    str << duration_cast<microseconds>(dt).count()*1e-3 << " ms";
    return str.str();
}

int main()
{
    volatile double x=34.234;
    volatile double y;
    constexpr auto MAX_ITER=100'000'000;
    const auto t0=currentTime();
    for(int i=0;i<MAX_ITER;++i)
        y=std::ceil(x);
    const auto t1=currentTime();
    for(int i=0;i<MAX_ITER;++i)
        y=cvCeil(x);
    const auto t2=currentTime();
    std::cout << "std::ceil: " << toString(t1-t0) << "\n"
                 "cvCeil   : " << toString(t2-t1) << "\n";
}

我在Intel Core i7-3930K 3.2 GHz上在GCC 8.3.0,glibc-2.27,Ubuntu 18.04.1 x86_64上使用-O3选项进行测试。

使用-sse4编译时的输出:

std::ceil: 39.357 ms
cvCeil   : 143.224 ms

没有-sse4编译时的输出:

std::ceil: 274.945 ms
cvCeil   : 146.218 ms

这很容易理解:SSE4.1引入了ROUNDSD指令,这基本上是std::round的功能。在此之前,编译器必须执行一些比较/条件移动技巧,并且还必须确保这些技巧不会溢出。因此,cvCeil版本牺牲了value>INT_MAX的明确定义,从而加快了对其明确定义的值的处理。对于其他人,它具有未定义的行为。

© www.soinside.com 2019 - 2024. All rights reserved.