Java中測試程序代碼運行時間的方式有兩種:測試
第一種:以毫秒爲單位計算的。程序
long startTime=System.currentTimeMillis();im
//下面是一些測試代碼時間
for(int i=0;i<10000;i++){tar
System.out.println("當前是:"+i);
}
long endTime=System.currentTimeMillis();
System.out.println("當前程序耗時:"+(endTime-startTime)+"ms");
第二種:以納秒爲單位計算的。
long startTime=System.nanoTime();
//下面是一些測試代碼
for(int i=0;i<10000;i++){
System.out.println("當前是:"+i);
}
long endTime=System.nanoTime();
System.out.println("當前程序耗時:"+(endTime-startTime)+"ns");
測試程序若是須要高精確時間,通常會選擇第二種,
測試程序若是須要通常精確時間,通常會選擇第一種,
時間換算:
1小時=60分鐘
1分鐘=60秒
1秒=1000毫秒
1毫秒=1000微秒
1微秒=1000納秒
1納秒=1000皮秒