Abel Callejo
Abel Callejo

Reputation: 14939

How do I measure how long the program is executed

I am creating a Java Application where the OS's System Clock is adjusted from time to time. (so it's like a peer-to-peer NTP experiment)

I am looking for a Java construct that is something like a virtual clock where in I can still get the age of the application in milliseconds from the time it was executed. Because if I will always just use System.currentTimeMillis(), it might give me false age of the application.

Is there something like that? without actually creating another thread solely for it?

Upvotes: 0

Views: 515

Answers (2)

Gerret
Gerret

Reputation: 3046

To calculte the elapsed time of your program you have multiple possibilities. Not all will fit your program because your system time could be change while your program is running.

currentTimeMillis()

With that method you get the current time of your system in millisecounds. If you want to calculate the runnning time of your program you could save the currentTime in a long variable. When you want the time the program is needed, you just simply subtract the currentTime now with your saved one.

Save the time when your program starts!

long start = System.currentTimeMillis();

Subtract the end time and the start time!

long need = System.currentTimeMillis() - start;

Keep in mind that if you change the system time you get a wrong time!

nanoTime()

With nanoTime you get the elapsed time of your Virtual Java Machine in nanosecounds. If you want to calculate the elapsed time, you have to do the same like with currentTimeMillis(). At the beginning you save the time and at the end you substract it.

Save the time when your program starts!

long start = System.nanoTime();

Subtract the end time and the start time!

long need = (System.nanoTime() - start) / 1000000; // divide to get millisecounds

Keep in mind that you get the right time, even if you change the system time, because you use the time of the Virtual Java Machine!

Difference

You only get the right elapsed time with System.nanoTime(). You should not use System.currentTimeMillis(), unless you do not mind that your result is wrong. currentTimeMillis() is to measure "wall-clock" time. When your system time is updateing, you simply get a wrong time. nanoTime() is actully mad for that, that you calculate the elapsed time.

Upvotes: 1

GerritCap
GerritCap

Reputation: 1626

No way to do this directly in Java, the only solution to this is to record the time differences applied to the system clock and takes this into account in your application.

Of course this depends greatly on the underlying operating system and the tools used to adjust the system clock.

Upvotes: 1

Related Questions