使用Date类的getTime()方法
下面是示例代码,比如你要统计代码的执行时间:
import java.util.Datepublic class Test {
public 凯兆旁static void main(String[] args) {
猜迹 long begin = new Date().getTime()
double d = 4
for (int i = 0 i < 200000 i++){
d += 4
}
System.out.println(d)
long end = new Date().getTime()
System.out.println(end - begin)
}
}
下面再看一下getTime的定义:
/*** Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT
* represented by this <tt>Date</tt> object.
*
* @return 盯橡 the number of milliseconds since January 1, 1970, 00:00:00 GMT
* represented by this date.
*/
public long getTime() {
return getTimeImpl()
}
milliseconds就是微妙的意思,所以getTime的精度是微妙
“java小程序”就是要谈历脊Java Applet吧,写了一个applet,精确到1纳秒=0.001微秒=0.000001豪秒
import java.applet.Applet
import java.awt.Graphics
import java.awt.event.KeyEvent
import java.awt.event.KeyListener
public class Test extends Applet {
private static final long serialVersionUID = 1L
final private long START_TIME=System.nanoTime()
public void init(){
this.addKeyListener(new KeyListener(){
@Override
public void keyTyped(KeyEvent e){
if(e.getKeyChar()=='\n'烂丛) repaint()
}
@Override
public void keyPressed(KeyEvent e) {}
@Override
public void keyReleased(KeyEvent e) {}
})
}
public void paint(Graphics 含渗g){
long t=System.nanoTime()-START_TIME
g.drawString("程序已运行"+t+"纳秒",5, 30)
g.drawString("约"+(t/1000000000.0)+"秒, 回车刷新", 5, 50)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)