gpt4 book ai didi

c++ - 如何使这个颜色百分比函数更快? C++

转载 作者:太空狗 更新时间:2023-10-29 23:32:46 25 4
gpt4 key购买 nike

extern inline double getColorPercentage(uint8_t *pixel, uint8_t *pixel2) {
//pixel 1 is 255, 255, 255
//pixel 2 is 0, 0, 0
//match is 0

//pixel 1 and 2 is 255, 255, 255
//match is 1.0
return (255-fabs(pixel[2] - pixel2[2])) * (255-fabs(pixel[1] - pixel2[1])) * (255-fabs(pixel[0] - pixel2[0])) /16581375.0;
}

我写了这个函数并尝试优化它,希望它能进一步优化。我经常使用它,有人知道如何提高它的性能吗?

最佳答案

您有很多不必要的 intfloat 的转换正在进行。除以常数也可以转换为乘法。这是一个可能更有效的版本:

inline double getColorPercentage(const uint8_t *pixel, const uint8_t *pixel2)
{
const double scale = 1.0 / (255.0 * 255.0 * 255.0); // compile-time constant
int m0 = 255 - abs(pixel[0] - pixel2[0]); // NB: use std::abs rather than fabs
int m1 = 255 - abs(pixel[1] - pixel2[1]); // and keep all of this part
int m2 = 255 - abs(pixel[2] - pixel2[2]); // in the integer domain
int m = m0 * m1 * m2;
return (double)m * scale;
}

与往常一样,您应该仔细对原始版本和任何优化版本进行基准测试和分析,并注意使用一种编译器和目标平台进行的优化可能对另一种编译器和目标平台没有用。

关于c++ - 如何使这个颜色百分比函数更快? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30893748/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com