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
Related
So guys, I got this tricky question. I'm trying to make a program using GUI interface that counts how long took the user to write down the input. I got more or less the idea of what I need but sadly I lack the knowledge on how to make it. An interface that counts seconds and at the end shows how many seconds took you to answer the questions. I already made the GUI questions input/output. if anyone knows how to make a timer with GUI interface I would appreciate it.
You can use System.currentTimeMillis() which returns the current time in milliseconds e.g.
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {
// Record time before input
long startTime = System.currentTimeMillis();
int nasc = Integer.parseInt(JOptionPane.showInputDialog(null, "when were u born?"));
int act = Integer.parseInt(JOptionPane.showInputDialog(null, "which year are you in?"));
int cal = act - nasc;
System.out.println("You are " + cal + "years old");
// Current time - start time = elapsed milliseconds
System.out.println("Total elapsed time: " + (System.currentTimeMillis() - startTime) / 1000 + " sec");
// Display the message in GUI
JOptionPane.showMessageDialog(null,
"Total elapsed time: " + (System.currentTimeMillis() - startTime) / 1000 + " sec");
}
}
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
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.");
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));
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.