欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java計(jì)算程序代碼執(zhí)行時(shí)間的方法小結(jié)

 更新時(shí)間:2017年11月01日 08:59:32   作者:左正  
這篇文章主要介紹了Java計(jì)算程序代碼執(zhí)行時(shí)間的方法,結(jié)合實(shí)例形式總結(jié)分析了java采用毫秒數(shù)及納秒數(shù)計(jì)算程序運(yùn)行時(shí)間的相關(guān)操作技巧,需要的朋友可以參考下

本文實(shí)例總結(jié)了Java計(jì)算程序代碼執(zhí)行時(shí)間的方法。分享給大家供大家參考,具體如下:

有時(shí)候?yàn)榱伺挪樾阅軉栴},需要記錄完成某個(gè)操作需要的時(shí)間,我們可以使用System類的currentTimeMillis()方法來返回當(dāng)前的毫秒數(shù),并保存到一個(gè)變量中,在方法執(zhí)行完畢后再次調(diào)用 System的currentTimeMillis()方法,并計(jì)算兩次調(diào)用之間的差值,就是方法執(zhí)行所消耗的毫秒數(shù)。

如方法一:

long startTime = System.currentTimeMillis(); //獲取開始時(shí)間
doSomething(); //測試的代碼段
long endTime = System.currentTimeMillis(); //獲取結(jié)束時(shí)間
System.out.println("程序運(yùn)行時(shí)間:" + (endTime - startTime) + "ms"); //輸出程序運(yùn)行時(shí)間

第二種方法是以納秒為單位計(jì)算的(使用SystemnanoTime()方法):

long startTime=System.nanoTime(); //獲取開始時(shí)間
doSomeThing(); //測試的代碼段
long endTime=System.nanoTime(); //獲取結(jié)束時(shí)間
System.out.println("程序運(yùn)行時(shí)間: "+(endTime-startTime)+"ns");

示例代碼一:

public static void main(String[]args){
 String str="";
 long starTime=System.currentTimeMillis();
 //計(jì)算循環(huán)10000的時(shí)間
 for(int i=0;i<10000;i++){
  str=str+i;
 }
 long endTime=System.currentTimeMillis();
 long Time=endTime-starTime;
 System.out.println(Time);
 StringBuilder bulider=new StringBuilder("");
 starTime=System.currentTimeMillis();
 for(int j=0;j<10000;j++){
  bulider.append(j);
 }
 endTime=System.currentTimeMillis();
 Time=endTime-starTime;
 System.out.println(Time);
}

示例代碼二:

public class Main {
 /**
 * 計(jì)算兩個(gè)時(shí)間點(diǎn)直接逝去的毫秒數(shù)
 *
 */
 public void computeAndDisplayElapsedTime() {
  long startTime = System.currentTimeMillis();
  for (int i = 0; i < 10; i++) {
   try {
    Thread.sleep(60);
   } catch (InterruptedException ex) {
    ex.printStackTrace();
   }
  }
  long endTime = System.currentTimeMillis();
  float seconds = (endTime - startTime) / 1000F;
  System.out.println(Float.toString(seconds) + " seconds.");
 }
 /**
 * 啟動(dòng)程序
 */
 public static void main(String[] args) {
  new Main().computeAndDisplayElapsedTime();
 }
}

輸出結(jié)果類似:

```out
0.609 seconds.

更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《java日期與時(shí)間操作技巧匯總》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》和《Java緩存操作技巧匯總

希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論