10

I want to calculate time difference in seconds between to time instants. For example, during execution of the program, I set the value of a variable and after some time I change it again. What was the time difference between the recent change of value from the previous value?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Space Rocker
  • 787
  • 3
  • 11
  • 25
  • possible duplicate of [In Java, how do I get the difference in seconds between 2 dates?](http://stackoverflow.com/questions/1970239/in-java-how-do-i-get-the-difference-in-seconds-between-2-dates) – moinudin Dec 25 '10 at 23:53

4 Answers4

14

You can use System.currentTimeMillis() to save the current time at one millisecond resolution. Just save the time whenever the first event occurs (better use a long var to hold that value) and again when the 2nd event occurs. The difference divided by 1000 will give you time difference in seconds.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
yurib
  • 8,043
  • 3
  • 30
  • 55
5

You can do something as simple as this:

long begin = System.currentTimeMillis();
doWork();
long end = System.currentTimeMillis();

long dt = end - begin;

More mature way (especially, if you need to do it many time in many places) is using a library. Look at perf4j. You can put @Profiled annotation on methods and it will automatically generate some statistics and write it to a log file.

Roman
  • 64,384
  • 92
  • 238
  • 332
3

Store the current time when you need to as retrieved from System.nanoTime(), and subtract any two of these values to get the difference in nanoseconds.

(By integer division first by a million and then float by a thousand you get a time in seconds with three decimal places, which prints nicely.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Thorbjørn Ravn Andersen
  • 73,784
  • 33
  • 194
  • 347
  • You could just divide by a billion rather than divide by a million and then a thousand. – Peter Lawrey Dec 26 '10 at 08:16
  • @Peter, that either gives nine decimals or none. I like it with three. – Thorbjørn Ravn Andersen Dec 26 '10 at 10:15
  • You should be using double rather than float. I missed that you were trying to get seconds to three decimal places. I do something similar except I prefer six decimal places. ;) – Peter Lawrey Dec 26 '10 at 13:11
  • @Peters, I am not a native speaker so please let me know how I could rephrase it so that it is very clear that that is the purpose. Also, out of curiousity how frequently do you have time differences measured in milliseconds that will not fit in a float? – Thorbjørn Ravn Andersen Dec 26 '10 at 23:45
1

Just fetch it from the system and store in long data. You can do math on those longs to figure out the time differential.

long start = System.currentTimeMillis();

//do stuff
//do more stuff

long end = System.currentTimeMillis();
zellio
  • 31,308
  • 1
  • 42
  • 61