优化浮点除法和转换操​​作 [英] Optimizing a floating point division and conversion operation

查看:100
本文介绍了优化浮点除法和转换操​​作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下公式

float mean = (r+b+g)/3/255.0f;

我要加快速度。主要有以下几种preconditions

I want to speed it up. There are the following preconditions

0<= mean <= 1  and 0 <= r,g,b <= 255 and r, g, b are unsigned chars

所以,如果我尝试使用的事实,8 >>就像是除以256,我使用类似

so if I try to use the fact that >> 8 is like dividing by 256 and I use something like

float mean = (float)(((r+b+g)/3) >> 8);

这将始终返回0有没有办法跳过昂贵的浮动分工和仍然在0和1之间的平均结了?

this will always return 0. Is there a way to skip the costly float division and still end up with a mean between 0 and 1?

推荐答案

$ P $您的部门对转换成multiplicable常数:

Pre-convert your divisions into a multiplicable constant:

a / 3 / 255

是相同的

a * (1 / (3 * 255))

所以pre-计算:

so pre-compute:

const float AVERAGE_SCALE_FACTOR = 1.f / (3.f * 255.f)

然后就去做

float mean = (r + g + b) * AVERAGE_SCALE_FACTOR;

由于乘以通常比划分快得多。

since multiplying is generally a lot faster than dividing.

这篇关于优化浮点除法和转换操​​作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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