likeIT
likeIT

Reputation: 307

Running time of the program

How can I "from program" (I mean before I do "final return" I want to print this time) to find out the time my program was running?

thanks in advance

edited

thank You very much for all answers, but I have very short program, is there any other way to find out the time in micro or nano seconds? cause using the method below I receive 0

Upvotes: 2

Views: 1061

Answers (3)

Mike Baranczak
Mike Baranczak

Reputation: 8374

Timing the main method, like aioobe suggests, is the simplest way to do it. But it may not work for multithreaded programs, or if the program is terminated by pressing ^C, or by System.exit(), or by an uncaught exception.

If you want to be notified when the program terminates, you can register a listener with Runtime.addShutdownHook().

Upvotes: 2

Are you planning to use this for profiling purposes? If so, you could use jvisualvm to profile you application. In fact, if you're running jdk above 1.6 update 7, you already have it: just type

jvisualvm

in console and have fun!

Upvotes: 0

aioobe
aioobe

Reputation: 421280

When the program starts, you do

long startTime = System.currentTimeMillis();

then right before you return from the main method, you do

long duration = System.currentTimeMillis() - startTime;
System.out.println("Program executed for " + duration + " milliseconds");

Upvotes: 8

Related Questions