How to print time elapsed (seconds) java - java

in my run method of a game loop I tried to print the time the program has been running in java. I simply tried System.out.println(System.nanoTime() / 1000000); because that's how many milliseconds are in a second.(if you didn't know) It prints the seconds near the end but I wanted exact seconds for testing purposes. I searched online and someone suggested using the same formula I thought of. Can anyone give an exact one?

Store previous time in a private member.
private long previousTime;
Initialize it in the constructor.
previousTime = System.currentTimeMillis();
Compare it with current time in run method (each iteration of game loop)
long currentTime = System.currentTimeMillis();
double elapsedTime = (currentTime - previousTime) / 1000.0;
System.out.println("Time in seconds : " + elapsedTime);
previousTime = currentTime;

In addition to the other answers provided, you could use a standard library StopWatch, like the one provided by Google's Guava API:
Stopwatch stopwatch = new Stopwatch();
stopwatch.start();
calculate();
stopwatch.stop(); // optional
long Seconds= stopwatch.elapsedMillis() / 1000000; // equals 1 second

You can use System.currentTimeMillis to get the current time in milliseconds.
If you pick this value at the start of your application and at the end, the subtraction of both values will give you the time your application was running.
final long start = System.currentTimeMillis();
// your code here...
final long end = System.currentTimeMillis();
System.out.println("The program was running: " + (end-start) + "ms.");
If you want it in seconds, just divide it with 1000 like you mentioned.
System.out.println("The program was running: " + ((double)(end-start)/1000.0d) + "ms.");

Related

Why would the same code be shorter inside a for loop?

So I've written a rather silly program just to work with nanoTime a bit. I wanted to be able to check execution times of small bits of code so I figure nanoTime would be the best. I wanted to determine the average execution time of this short bit of code, so I put it inside a for loop. However, when inside the for loop, the average drops to about 6,000 nano seconds less. I know this isn't a huge difference on small code but I am curious why it would be any different for the same exact code?
here are the two blocks that yield different times:
this one is an average of about 8064 nano seconds:
long start, end, totalTime;
double milliseconds, seconds, minutes, hours, days, years;
totalTime = 0;
start = System.nanoTime();
milliseconds = System.currentTimeMillis();
seconds = milliseconds/1000;
minutes = seconds/60;
hours = minutes/60;
days = hours/24;
years = days/365;
end = System.nanoTime();
totalTime = end-start;
and this one is an average of about 2200 nano seconds:
long start, end, totalTime;
double milliseconds, seconds, minutes, hours, days, years;
totalTime = 0;
for(int i = 1; i < 11; i++){
start = System.nanoTime();
milliseconds = System.currentTimeMillis();
seconds = milliseconds/1000;
minutes = seconds/60;
hours = minutes/60;
days = hours/24;
years = days/365;
end = System.nanoTime();
totalTime += end-start;
System.out.println(end-start); //this was added to manually calc. the average to
//make sure the code was executing properly. does not effect execution time.
}
and then to find the average you take totalTime*.1
This is exactly what you should expect from any Java program. The Java runtime, specifically the JIT compiler, will optimize code more heavily the more it gets run over the lifetime of the program. You should expect code to speed up after getting run multiple times.

How to Calculate How Much Time the Program Consumed While Running

I am trying to calculate the time consumed by the program. But what is the difference between the two methods displayed below?
System.currentTimeMillis() % 1000
System.currentTimeMillis() / 1000
I assume by the fact that you're dividing by 1000 you want it in seconds?
Regardless, the modulus operator % is not what you want here, it gives you the remainder of the division by the second operand.
To get the runtime of some code, get the current time before execution, and after execution. The runtime will the the difference between the two.
System timeBefore = System.currentTimeMillis();
//PUT CODE HERE
System timeAfter = System.currentTimeMillis();
System timeDelta = timeAfter = timeBefore;
System.out.println("Runtime was " + timeDelta + " millis"); //display milliseconds
System.out.println("Runtime was " + (timeDelta / 1000) + " seconds"); //display seconds
You may want to try something like this:
public static void main(String[] args) throws InterruptedException{
long t1 = System.nanoTime();
Thread.sleep(3000L);//do your work here
long t2 = System.nanoTime();
long result = t2 - t1;
result = result / 1000000000;
System.out.println(result);
}
This will give you time in seconds...
Output:
3
Explanation of the two methods
System.currentTimeMillis() / 1000
/ is the division operator. It will return you the result of System.currentTimeMillis() divided by 1000. This is often used to convert miliseconds to seconds.
System.currentTimeMillis() % 1000
% is the remainder operator.
It will return the remainder that is left after the division by 1000 (modulus).
Oracle provides a full list of Java-Operators.
Example for the question from the title
If you want to get the total uptime off your application, you can easily receive it from the Java Runtime:
ManagementFactory.getRuntimeMXBean().getUptime()
This will return the runtime of your programm in milliseconds. By dividing it with 1000 you will get the seconds your programm is running.
Advantage:
You don't have to handle the time measurement yourself

Nano and milliseconds

long startTime = System.nanoTime();
long startTimer = System.currentTimeMillis();
M = app.decriptare_simpla(C);
long endTime = System.nanoTime();
long stopTimer = System.currentTimeMillis();
//mesajul initial dupa decriptare
System.out.println("M : " + M.toString());
System.out.println("Decriptarea a durat: " + (endTime - startTime));
System.out.println("Decriptarea a durat: " + (stopTimer - startTimer));
This gave me:
Decriptarea a durat: 14811776
Decriptarea a durat: 15
What I want to ask is how much of a second are those 2 numbers? I mean are they, 0.15, 0.015, 0.0015...? I'd like to print them in that manner, not as an long but don't know how many decimals to add. Same question for the other number.
The conversions follow the usual rules for Standard SI Units:
long nanoSeconds = ...
double microSeconds = nanoSeconds / 1e3;
double milliSeconds = microSeconds / 1e3;
double seconds = milliSeconds / 1e3;
// Shortcuts:
double milliSeconds = nanoSeconds / 1e6;
double sconds = nanoSeconds / 1e9;
For some conversions, you can also have a look at the TimeUnit class: It allows conversions between values in different time units, for example
long microSeconds = NANOSECONDS.toMicros(nanoSeconds);
However, it unfortunately does not allow time spans given in double precision, but only as long values.
An aside, also mentioned in the comments: Measuring time spans in the order of 10-15ms usually makes no sense due to the limited resolution of the internal timer.
Have you tried like this
System.out.println(TimeUnit.SECONDS.convert((endTime - startTime), TimeUnit.NANOSECONDS));
System.out.println(TimeUnit.SECONDS.convert((stopTimer - startTimer), TimeUnit.MILLISECONDS));

how correctly display nanotime to second conversion

I have a BFS algorithm to solve the 8-Puzzle, and one of the project requirements is to output the amount of time it takes to find the shallowest solution.
I am using System.nanoTime() to keep track of the applications run time because it solves the majority of the given puzzles in well under a second.
The problem i am having is whem i convert my nanoTime to seconds, it displays in a weird format.
the following code is used:
final long startTime = System.nanoTime();
//algorithm code removed for simplicity this all functions correctly
final long duration = System.nanoTime() - startTime;
final double seconds = ((double)duration / 1000000000);
System.out.println("Nano time total: " + duration);
System.out.println("solution Time : " + seconds + " Seconds");
This produces the output:
Nano time total: 916110
solution time : 9.1611E-4 Seconds
I have also tried using floats to represent the values.
is anybody able to provide a better way to convert/display, maybe use a format output statement?
Thanks for taking the time to read my question.
I think you need: DecimalFormat
System.out.println("solution Time : " + new DecimalFormat("#.##########").format(seconds) + " Seconds");
System.out.format("solution Time : %f Seconds", seconds);
for the classic, non-exponential floating point number.

Varying execution time of for loop in Java

I am a newbie in Java. I have done following coding.
class TimeComplex{
public static void main(String []args){
long startTime, stopTime, elapsedTime;
//first call
startTime = System.currentTimeMillis();
System.out.println("\nstart time : " + startTime + "\n");
calcForLoop();
stopTime = System.currentTimeMillis();
System.out.println("stop time : " + stopTime + "\n");
elapsedTime = stopTime - startTime;
System.out.println("\t1st loop execution time : " + elapsedTime+ "\n");
//second call
startTime = System.currentTimeMillis();
System.out.println("start time : " + startTime + "\n");
calcForLoop();
stopTime = System.currentTimeMillis();
System.out.println("stop time : " + stopTime + "\n");
elapsedTime = stopTime - startTime;
System.out.println("\t2nd loop execution time : " + elapsedTime + "\n");
//third call
startTime = System.currentTimeMillis();
System.out.println("start time : " + startTime + "\n");
calcForLoop();
stopTime = System.currentTimeMillis();
System.out.println("stop time : " + stopTime + "\n");
elapsedTime = stopTime - startTime;
System.out.println("\t3rd loop execution time : " + elapsedTime + "\n");
}
static void calcForLoop(){
for(long i = 12_85_47_75_807L; i > 0; i--);
}
}
The code runs a for-loop for a long period of time just to increase the execution time of the program. When the calcForLoop() is called for the first time the execution time of the program is maximum when the same method is called for the second time the program takes lesser time than the first call and the third call to the method calcForLoop() is less than or equal to the second execution time. I ran this program for 5-6 times and the I got the same pattern of execution time.
My question is why does this happen when the code to execute remains same for all the three time. Is there any code optimization that takes place by the compiler or it is dependent on the operating system environment. What sort of optimization is done by compiler when there is repeated execution of the same block of code like in this case?
The JIT (just in time) compiler compiles code that the JVM detects is being executed a lot, which accounts for the increase in performance. There may actually be a brief reduction in performance while such compilation is taking place.
It is usual to allow for this effect in performance testing - you execute the code a few thousand times, then start your benchmark.
Loop nest optimization is an optimization technique that applies a set of loop transformations for the purpose of locality optimization or parallelization. One classical usage is to reduce memory access latency or the cache bandwidth necessary due to cache reuse for some common linear algebra algorithms.
If you want to be more accurate in measuring the elapsed time you must use System.nanoTime() instead of using System.currentTimeMillis().
And of course what Bohemian mentioned about JIT do comes into picture.

Categories