How can I count the time it takes a function to co

2019-01-30 10:23发布

I need to measure the time it takes for a function to complete in Java. How can I do that?

Note:

I want to measure the function's time consumption, not that of the full program.

10条回答
We Are One
2楼-- · 2019-01-30 11:01
long start = System.nanoTime();    
methodToBeTimed();
long elapsedTime = System.nanoTime() - start;
查看更多
女痞
3楼-- · 2019-01-30 11:05

If you are using Guava, consider using the Stopwatch, e.g.:

final Stopwatch sw = Stopwatch.createStarted();
methodToBeTimed();
final long elapsedMillis = sw.elapsed(TimeUnit.MILLISECONDS);
查看更多
等我变得足够好
4楼-- · 2019-01-30 11:07

The profiler is the right answer if you have more than one function.

Another problem that I see with all the suggestions given so far is that they work fine for a single function, but your code will be littered with timing stuff that you can't turn off.

If you know how to do aspect oriented programming, it's a good way to keep the timing code in one place and apply it declaratively. If you use something like Log4J to output the values, you'll have the option of turning it off or on. It's a poor man's profiler.

Have a look at AspectJ or Spring's AOP.

查看更多
啃猪蹄的小仙女
5楼-- · 2019-01-30 11:08

All of the code snippets above measure the approximate time elapsed from the time the method was invoked to the time the method returns/throws an exception. Such techniques do not address thread scheduling, pauses due the GC, etc.

Yes, some profilers will do a reasonable job.

If you are using Java 1.6 onwards, you can use the JMX based VM management and monitoring support. For example, you may find ThreadMXBean.getCurrentThreadCpuTime() of value. Calculating the difference of this value before and after the method invoke will give you:

"... the total CPU time for the current thread in nanoseconds. The returned value is of nanoseconds precision but not necessarily nanoseconds accuracy. If the implementation distinguishes between user mode time and system mode time, the returned CPU time is the amount of time that the current thread has executed in user mode or system mode."

If your method spawns off worker threads, then your computation will need to get far more elaborate ;-)

In general, I recommend nosing around the java.lang.mangement package.

查看更多
疯言疯语
6楼-- · 2019-01-30 11:09

If you want to get current time, use java.util.Date.

查看更多
\"骚年 ilove
7楼-- · 2019-01-30 11:11

Use either System.currentTimeMillis() or System.nanoTime():

int someMethod() {
    long tm = System.nanoTime();
    try {
        ...
    } finally {
        tm = System.nanoTime()-tm;
        System.out.println("time spent in someMethod(): " + tm + "ns");
    }
}
查看更多
登录 后发表回答