gav*_*gav 12 c overhead switch-statement
我是一个相当称职的Java程序员,对C来说很新.我正在尝试优化具有四种操作模式的例程.
我遍历图像中的所有像素,并根据传递的"模式"计算新的像素值.
我的问题是关于两个嵌套for循环中switch语句的开销.我对任何有关基本C语句,数学和逻辑运算的相对效率的文档链接感兴趣.
代码如下:
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
switch (mode) /* select the type of calculation */
{
case 0:
weight = dCentre / maxDistanceEdge;
case 1:
weight = (float)x/width;
break;
case 2:
weight = (float)y/height;
break;
case 3:
weight = dBottomLeft / maxDistanceCorner;
break;
case 4:
weight = dTopRight / maxDistanceCorner;
break;
default:
weight = 1;
break;
}
// Calculate the new pixel value given the weight
...
}
}
Run Code Online (Sandbox Code Playgroud)
如果这是超过5000 x 5000像素的图像,你会期望看到很多开销吗?我试过做一些测试,但我的结果到处都是,因为系统(移动设备)有各种各样的东西在后台运行,可能会扭曲结果.
另一种选择是为每种模式设置一个单独的方法,每种方法都有自己的四个循环.这显然会引入冗余代码,但效率是这里游戏的名称.
提前致谢!
GAV
Jim*_*uck 19
Switch语句编译为连续值的跳转表和稀疏值的一堆if-else语句.在任何情况下,如果您关心性能,则不希望在内部循环中使用switch语句进行图像处理.你想改为如下.
另外,请注意我将权重计算移出内部循环(并为了实现此目的而交换了案例2的循环).这种思维方式,从内循环中移出东西,将为您提供您想要的性能.
switch (mode) /* select the type of calculation */
{
case 0:
weight = dCentre / maxDistanceEdge;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
// Calculate the new pixel value given the weight
...
}
}
break;
case 1:
for (x = 0; x < width; x++) {
weight = (float)x/width;
for (y = 0; y < height; y++) {
// Calculate the new pixel value given the weight
...
}
}
break;
case 2:
// note - the loops have been swapped to get the weight calc out of the inner loop
for (y = 0; y < height; y++) {
weight = (float)y/height;
for (x = 0; x < width; x++) {
// Calculate the new pixel value given the weight
...
}
}
break;
case 3:
weight = dBottomLeft / maxDistanceCorner;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
// Calculate the new pixel value given the weight
...
}
}
break;
case 4:
weight = dTopRight / maxDistanceCorner;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
// Calculate the new pixel value given the weight
...
}
}
break;
default:
weight = 1;
for (x = 0; x < width; x++) {
for (y = 0; y < height; y++) {
// Calculate the new pixel value given the weight
...
}
}
break;
// etc..
}
Run Code Online (Sandbox Code Playgroud)
Mic*_*hne 10
如果效率比代码大小更重要,那么您应该创建冗余例程.case语句是你在C中可以做的较低开销之一,但它不是零 - 它必须根据模式进行分支,因此需要时间.如果你真的想要最大性能,那么即使以重复循环为代价,也要将情况从循环中解脱出来.
Switch语句尽可能高效.他们被编译成跳转表.实际上,这就是为什么切换受限制的原因:您只能编写一个开关,您可以根据固定值编译跳转表.
归档时间: |
|
查看次数: |
8495 次 |
最近记录: |