Timing how long something takes in seconds - java

I am trying to time how long something takes and i cant get it to spit out the seconds without rounding. Here is what ive tried:
long beginTime = System.nanoTime();
//Do something
long endTime = System.nanoTime();
double time = (endTime-beginTime)/1000000000;
I've also tried using the function TimeUnit.NANOSECONDS.toSeconds and that rounds the number as well.
It should give me 1.45 seconds but it gives me 1 and it should be 1445.7191 Milliseconds but it gives me 1446.

the result of your divison is implicitly casted to int, change your divisor to a double value (add a 'd' at the end): 1000000000d
long beginTime = System.nanoTime();
// Do something
long endTime = System.nanoTime();
double time = (endTime - beginTime) / 1000000000d;
System.out.println(time);

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

How to print time elapsed (seconds) 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.");

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));

Formatting time properly from milliseconds

I am timing an event like this:
seconds = System.currentTimeMillis() / 1000;
// Something happens here
time = System.currentTimeMillis() / 1000 - seconds;
and then I have attempted to format it:
String Time = String.format("%d min, %d sec",
TimeUnit.MILLISECONDS.toMinutes(time),
TimeUnit.MILLISECONDS.toSeconds(time) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)));
and the results don't make any sense, the minutes are thousands but the seconds seem to be normal numbers. What is the proper way to format the time?
long milliseconds = System.currentTimeMillis()%1000;
long seconds = (System.currentTimeMillis()/1000)%60;
long minutes = (System.currentTimeMillis()/(60*1000))%60;
long hours = (System.currentTimeMillis()/(60*60*1000));
Leave out whatever parts you don't want and remove the modulus from the highest one you do.

Categories