在进行算法学习的时候,要比较不同算法之间的优劣就要考虑运行速度的问题。如何检测程序的运行时间就是我们必须要了解的一个问题。这里来说一下。
0.实现思路
一般的实现思路就是获取系统时间,计算要测试程序运行前后的时间差,因为系统时间是以毫秒(millisecond)为单位,因此可以获得相对精确的运行时间。如果程序实在比较小,那就循环多次运行,比如10000次,这样可以更加清晰的看出运行速度。
1、获取系统时间
获取系统时间,用的是System.currentTimeMillis(). 看一下官方API给出的说明:
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.
Returns:
the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC.
该方法返回值是从1970年1月1日凌晨到此时刻的毫秒数!(可以算算long最多可以计时计到啥时候,哈哈!)
这里注意一下,我们一般输出日期时间经常会用到Date这个类。例如:
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
System.out.println(df.format(new Date()));// new Date()为获取当前系统时间
其API表述如下:
The class Date represents a specific instant in time, with millisecond precision.
注意到Date类的时间精度也是毫秒级的。可以实现我们上面给出的代码一样的效果。实际上,查看一下Date类的源码就会发现:
public Date()
{
this(System.currentTimeMillis());
}
也就是说Date类也是调用了系统的时间,并对其进行了一系列封装处理。因此我们如果需要详细的信息,比如年份月份等可以使用Date类。而此处我们只需要知道毫秒差就可以了,就没必要用date类了,避免浪费。
2. 实现代码
代码实现就比较简单了,直接上代码:
long starTime=System.currentTimeMillis();
//计算循环10000的时间
for(int i=0; i<10000; i++)
{
//your code;
}
long endTime=System.currentTimeMillis();
long Time=endTime-starTime;
System.out.println(Time);
这样就可以得到程序运行的时间了,注意单位是毫秒。
下一篇将会给出两个实际应用的例子。