撰写代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | public class Main { /** * @param args */ public static void main(String[] args) { // TODO 自动生成的方法存根 double a,b; a=test1( 10 ); b=test2( 10 ); System.out.println(a); System.out.println(b); System.out.println(b/a); } public static double test1( int n) { double total= 0.0 ; double t= 0 .0d; for ( int i= 0 ;i<n;++i){ long t0,t1,t2; t0=System.nanoTime(); t1=System.nanoTime(); for ( int j= 0 ;j< 100000000 ;++j) { t+= 0 .1d; } t2=System.nanoTime(); total+=t2-t1-(t1-t0); } return total/n; } public static double test2( int n) { double total= 0.0 ; float t= 0 .0f; for ( int i= 0 ;i<n;++i){ long t0,t1,t2; t0=System.nanoTime(); t1=System.nanoTime(); for ( int j= 0 ;j< 100000000 ;++j) { t+= 0 .1f; } t2=System.nanoTime(); total+=t2-t1-(t1-t0); } return total/n; } } |
运行结果如下:
8.32064216E7
8.30583296E7
0.998220185447802
完。
double好慢
我发现我的测试程序有bug