编写程序到一定程度的,我们就不得不考虑成都所占用的内存、时间。那么如何获取程序执行的时间呢?需要用到currentTimeMillis方法。
在程序开始时获取一个时间,结束时获取一个时间,两者相减,即为程序所用时间。
下面程序时空语句执行一亿次所用的时间,参考程序如下:
1 public class GCXL132 {//主类 2 public static void main(String[] args) {//主函数 3 long starTime=System.currentTimeMillis();//当前时间赋给一个变量 4 //System.out.println(starTime);//输出开始时间 5 for(int i=0;i<10000;i++){//执行空循环 6 for(int j=0;j<10000;j++);//嵌套,共1亿次 7 } 8 long endTime=System.currentTimeMillis();//当前时间赋给一个变量 9 //System.out.println(endTime);//输出结束时间 10 long time=endTime-starTime;//计算所用时间 11 System.out.println("执行空循环1亿次所用时间:"+time);//输出时间 12 } 13 }