开发者

adding run time on my java program

i have my Java program and i would like 开发者_StackOverflow社区to add code that show the run time for calculating, but i have no idea how can i do that?


Measure like this:

long startTime = System.currentTimeMillis();

.... // code block you want to measure.

System.out.println("Execution took: "+(System.currentTimeMillis() - startTime));


Try the following:

        long start = System.currentTimeMillis();

        //Execute your code here

        long runtime = System.currentTimeMillis() - start;

        System.out.println("Runtime was "+runtime+" ms");

More about the System.currentTimeMillis() function here


The simplest way to do this is as follows:

public void foo() { 

    long start = System.currentTimeMillis();

    .

    .

    .

    System.out.println("foo took " +(System.currentTimeMillis() - start)+ " ms");

    return;

}

Alternatively, you can use a profiler.


It's quite simple and straightforward. Just use the System.currentTimeMillis() that will return the number of milliseconds (ticks) from the good same old date: 00.00 - 1 January 1970.

With this you can easily calculate the time used by your calculations:

long start = System.currentTimeMillis();

// dirty work

long elapsed = System.currentTimeMillis() - start;
System.out.println("Operation took "+elapsed+" millisecs.");

In addition another method, System.nanoTime()is present too. This method can have a greater accuracy according to the timer resolution of your machine and it can be used in the same identical way.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜