【发布时间】:2015-02-17 16:34:35
【问题描述】:
我正在使用下一个算法来执行最近邻调整大小。有没有办法优化它的速度?输入和输出缓冲区采用 ARGB 格式,尽管已知图像始终是不透明的。谢谢。
void resizeNearestNeighbor(const uint8_t* input, uint8_t* output, int sourceWidth, int sourceHeight, int targetWidth, int targetHeight)
{
const int x_ratio = (int)((sourceWidth << 16) / targetWidth);
const int y_ratio = (int)((sourceHeight << 16) / targetHeight) ;
const int colors = 4;
for (int y = 0; y < targetHeight; y++)
{
int y2_xsource = ((y * y_ratio) >> 16) * sourceWidth;
int i_xdest = y * targetWidth;
for (int x = 0; x < targetWidth; x++)
{
int x2 = ((x * x_ratio) >> 16) ;
int y2_x2_colors = (y2_xsource + x2) * colors;
int i_x_colors = (i_xdest + x) * colors;
output[i_x_colors] = input[y2_x2_colors];
output[i_x_colors + 1] = input[y2_x2_colors + 1];
output[i_x_colors + 2] = input[y2_x2_colors + 2];
output[i_x_colors + 3] = input[y2_x2_colors + 3];
}
}
}
【问题讨论】:
-
看起来它在计算复杂度方面是最优的。此处只能进行外观优化(例如尝试使用 memcpy 而不是输入
-
由于您假设每个像素有四个 8 位通道,您可以通过直接使用
uint32_t类型的元素来提高性能。这样,您可以将最内层循环中的四个赋值语句减少到一个,并且您也可以在那里删除几个乘法。 (只有当编译器已经在自己执行这样的优化时,这才无济于事。) -
注意:
x_ratio, y_ratio, y2_xsource, i_xdest容易出现未检测到的溢出。 -
x2, y2_x2_colors, i_x_colors可以简化为x递增 1,并且可以利用这一点获得更新的值。这类似于经典的Bresenham line drawing。抱歉 - 无需深入挖掘。 -
消除循环中的乘法。
标签: c++ c performance optimization