how correctly display nanotime to second conversion - java

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.

Related

Duration of minutes not working correctly in Java/Android

I am trying to display a rest time value in hours and minutes to my UI on an application I am finishing up.. I made use of another StackOverflow forum to figure this out and so far it is working okay, the time is displaying, but I think the maths is wrong somewhere..
I have two TextViews, one which displays active time in minutes, and another which displays rest time in hours and minutes (as the rest time will normally be a significantly longer period). The rest time is essentially 24hrs minus the active time.
So far, I have converted my stored active time string to an Int, subtracted that from the minute value for 24 hours (1440 minutes), then used the Duration method to convert that value to hours and minutes (hh:MM) which worked fine, the UI showed the correct subtracted value in hh:MM.
My problem is when I tried to split this into parts using a string, where my string is (restHours + " h" + restMinutes + " minutes") I get the hours and minutes value for the entire restTimeInt value (for example: 23h 1430minutes).
How can I change this so it displays the correct minutes value (for example: 23hr 40min)?
int activeTimeValue = Integer.parseInt(activityTime); // ex: 10 mins
int day = 1440;
int restTimeInt = day - activeTimeValue; // 1430 mins
Duration d = Duration.ofMinutes(restTimeInt);
int restHours = (int) d.toHours();
int restMinutes = (int) d.toMinutes();
restTimeTV.setText(restHours + " hr" + restMinutes + " mins");
Duration.minus() and Duration.toMinutesPart()
Now you’re at it, why not go all in on Duration and let it handle all math for you? With a little help it can even parse your string of minutes.
String activityTimeStr = "10"; // Minutes
Duration activityTime = Duration.parse("PT" + activityTimeStr + "M");
Duration restTime = Duration.ofDays(1).minus(activityTime);
System.out.format("Rest time: %s%n", restTime);
Output is:
Rest time: PT23H50M
So 23 hours 50 minutes, as expected. If you need those numbers, 23 and 50, for example for formatting for the user, as deHaar said, use the toMinutesPart method of Duration:
int restHours = Math.toIntExact(restTime.toHours());
int restMinutes = restTime.toMinutesPart();
System.out.format("Rest time: %d hours %d minutes%n", restHours, restMinutes);
Rest time: 23 hours 50 minutes

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

Time is not convering nanoseconds to seconds right

can someone catch if there is anythong wrong with my code. I am trying to time how long it is taking to do this factorial and convert it to seconds, but it seems to be printing out a wrong value. Thanks!!
long startTime = System.nanoTime();
BigInteger factorial_minute = doFactorial(50000);
long endTime = System.nanoTime();
String factorial_minute_str = factorial_minute.toString();
System.out.println("Largest n! in one minute = " + factorial_minute);
System.out.println("n! in one minute Amount of Digits: " + factorial_minute_str.length()); // Print the length also
System.out.println("Total execution time: " + (int)((endTime - startTime)/1000000000 + " seconds") );
The output is
Total execution time: 4 seconds
EDIT, I changed it to be 1000000000, but it seems like the output is still wrong.
One nanosecond is one billionth of a second, not one millionth. Add three more zeros to your divisor.
(endTime - startTime)/1000000000

Why does converting System.nanoTime() to a Calendar object give me the wrong current date?

If I understand correctly, using System.nanoTime() is a more accurate way of keeping a marker to the current time than System.currentTimeInMillis(), even if the system time was changed. So why is it that when I convert the long value of nanoTime() to a Calendar object, the output is wrong?
import java.util.Calendar;
public class Test {
public static void main(String[] args) {
Calendar c = Calendar.getInstance();
c.setTimeInMillis(System.currentTimeMillis());
System.out.println(c.get(Calendar.MONTH) + " " + c.get(Calendar.DATE) + " " + c.get(Calendar.YEAR) +
" " + c.get(Calendar.HOUR_OF_DAY) + ":" + c.get(Calendar.MINUTE) + ":" + c.get(Calendar.SECOND)
+ ":" + c.get(Calendar.MILLISECOND));
}
}
System.nanotime() javadoc suggests :
Returns the current value of the most precise available system timer, in nanoseconds.
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time. The value returned represents nanoseconds since some fixed but arbitrary time (perhaps in the future, so values may be negative). This method provides nanosecond precision, but not necessarily nanosecond accuracy. No guarantees are made about how frequently values change. Differences in successive calls that span greater than approximately 292 years (263 nanoseconds) will not accurately compute elapsed time due to numerical overflow.
For example, to measure how long some code takes to execute:
long startTime = System.nanoTime();
// ... the code being measured ...
long estimatedTime = System.nanoTime() - startTime;

Categories