java floatmath,将浮点值舍入到java中最接近的整数的最有效方法是什么?

I've seen a lot of discussion on SO related to rounding float values, but no solid Q&A considering the efficiency aspect. So here it is:

What is the most efficient (but correct) way to round a float value to the nearest integer?

(int) (mFloat + 0.5);

or

Math.round(mFloat);

or

FloatMath.floor(mFloat + 0.5);

or something else?

Preferably I would like to use something available in standard java libraries, not some external library that I have to import.

解决方案

public class Main {

public static void main(String[] args) throws InterruptedException {

for (int i = 0; i < 10; i++) {

measurementIteration();

}

}

public static void measurementIteration() {

long s, t1 = 0, t2 = 0;

float mFloat = 3.3f;

int f, n1 = 0, n2 = 0;

for (int i = 0; i < 1E4; i++) {

switch ((int) (Math.random() * 2)) {

case 0:

n1 += 1E4;

s = System.currentTimeMillis();

for (int k = 0; k < 1E4; k++)

f = (int) (mFloat + 0.5);

t1 += System.currentTimeMillis() - s;

break;

case 1:

n2 += 1E4;

s = System.currentTimeMillis();

for (int k = 0; k < 1E4; k++)

f = Math.round(mFloat);

t2 += System.currentTimeMillis() - s;

break;

}

}

System.out.println(String.format("(int) (mFloat + 0.5): n1 = %d -> %.3fms/1000", n1, t1 * 1000.0 / n1));

System.out.println(String.format("Math.round(mFloat) : n2 = %d -> %.3fms/1000", n2, t2 * 1000.0 / n2));

}

}

Output on Java SE6:

(int) (mFloat + 0.5): n1 = 500410000 -> 0.003ms/1000

Math.round(mFloat) : n2 = 499590000 -> 0.022ms/1000

Output on Java SE7 (thanks to alex for the results):

(int) (mFloat + 0.5): n1 = 50120000 -> 0,002ms/1000

Math.round(mFloat) : n2 = 49880000 -> 0,002ms/1000

As you can see, there was a huge performance improvement on Math.round from SE6 to SE7. I think in SE7 there is no significant difference anymore and you should choose whatever seems more readable to you.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值