com.android.internal.util (非公開)パッケージに FastMath というクラスがあり、
小数点丸め計算の高速版メソッドがありましたので、どれくらい高速なのか実験してみました。
実験用ソースコード
package com.adakoda.android.fastmathtest;
import android.app.Activity;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
public class FastMathTestActivity extends Activity {
// This is copy of com.android.internal.util.FastMath.round method
public static int round(float x) {
long lx = (long)(x * (65536 * 256f));
return (int)((lx + 0x800000) >> 24);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
long start = SystemClock.uptimeMillis();
{
float a = 0.1f;
for (int i = 0; i < 1000000; i++) {
// Math.round(a); // 1.java.lang.Math
round(a); // 2.com.android.internal.util.FastMath
}
}
long end = SystemClock.uptimeMillis();
Log.v("time[ms]", String.valueOf(end - start));
}
}
実験結果
単精度小数点を100万回丸め計算するのに要した時間は、
以下のとおり FastMath.round() の方が、java.lang.Math.round() より 約2.25倍高速でした(≠ 赤い彗星)。
- java.lang.Math.round() ・・・ 6,626 [ms]
- FastMath.round() ・・・ 2,940[ms]
なんだか懐かしい感じです。
