1. 通过System.currentTimeMillis()来获取当前时间,以毫秒数形式返回。 long java.lang.System.currentTimeMillis()
currentTimeMillispublic static long currentTimeMillis()
Returns the current time in milliseconds. Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.
See the description of the class Date for a discussion of slight discrepancies that may arise between "computer time" and coordinated universal time (UTC).
Returns:
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
所以我们可以这样统计代码段运行时间(毫秒):
long start=System.currentTimeMillis();
//your code
long end=System.currentTimeMillis();
long time = end -start;
这就是代码运行的毫秒数了。
public class CountTime {
public static void main(String args[])
{
long start=System.currentTimeMillis();
for (int i=0; i<1000000; i++)
{
for (int j=0; j<100000; j++)
{
for (int k=0; k<10000; k++)
{
int a = i*j;
a++;
}
}
}
try
{
Thread.sleep(1000);
} catch (InterruptedException e)
{
System.out.println("Interrupted");
}
long end=System.currentTimeMillis();
System.out.println("Run Time:"+(end-start));
}
}
2. 通过import java.util.Date; 中的Date对象来获取执行时间。
Date startDate= new Date();
//your code
Date endDate= new Date();
long time=endDate.getTime()-startDate.getTime();
这就是代码运行时间,也是毫秒为单位。

Don't forget System.nanoTime()
回复删除:)