posts - 195,  comments - 30,  trackbacks - 0
apps.hi.baidu.com/share/detail/33559179

Java 程序计时(Java Timing)
(1)如何精确给代码计时;

(2)计时机制本身的时间开销;

经典的程序计时利用Java API方法:System.currentTimeMillis(),在待测代码前后放置一个秒表(stopwatch),计算前后时间差即可。
下面是一个引自“”的stopwatch类,
import java.io.PrintStream;

final class Timer{ 

    private long startTime;
    private long endTime;
    public Timer() {   reset(); }

    public void start() {
        System.gc();
        startTime = System.currentTimeMillis();
    } 
    public void end() {
        System.gc();
        endTime = System.currentTimeMillis();
     }
    public long duration() {
        return (endTime - startTime);
    }
    public void printDuration( PrintStream out ) {
        long elapsedTimeInSecond = duration() / 1000;
        long remainderInMillis = duration() % 1000;
        out.println("\nTotal execution time:"
              + elapsedTimeInSecond + "."
                + remainderInMillis
                + " seconds");
    }
    public void reset() {
        startTime = 0;
         endTime = 0;
    }
    public static void main( String[] args ) {
        Timer timer = new Timer();
        timer.start();
        for (int i = 0; i < 500; i++) {
           System.out.print("#");
        }
        timer.end();
        timer.printDuration(System.out); }
}
这是一种常规做法。
在多线程环境中,线程切换由OS控制,因此两次掐表之间可能记录了被OS切换到的其它线程的执行时间,这期间甚至包含其它线程的长耗时I/O操作。
多次掐表然后求其平均可一定程度上平滑这种误差,然而,对于高精度要求,上述API秒表计时方式是有缺陷的。
Jesper 在“Use the JVM Profiler Interface for accurate timing”中描述了一种利用Java Virtual Machine Profiler Interface (JVMPI)的方法
发现了两个新的函数:System.currentTimeMillis()和System.nanoTime()。其中System.nanoTime()是1.5版以后的新函数。这两个函数都是返回当前系统的时间,只是System.nanoTime()返回的精度更高。
posted on 2011-09-26 23:15 luis 阅读(2189) 评论(0)  编辑 收藏 引用 所属分类: Java笔记

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

常用链接

留言簿(3)

随笔分类

随笔档案

文章分类

文章档案

友情链接

搜索

  •  

最新评论

阅读排行榜

评论排行榜