for(int i = 1; i < 10000; i++) {
Command nextCommand = getNextCommandToExecute();
}
I want to run the above program for 60 minutes. So instead of for loop I need to do something like-
long startTime = System.nanoTime();
do{
Command nextCommand = getNextCommandToExecute();
} while (durationOfTime is 60 minutes);
But I am not sure, how should I make this program to run for 60 miniutes.
Launch a background thread that sleeps for 60 minutes and exits:
Runnable r = new Runnable() {
#Override
public void run() {
try {
Thread.sleep(60 * 60 * 1000L);
}
catch (InterruptedException e) {
// ignore: we'll exit anyway
}
System.exit(0);
}
}
new Thread(r).start();
<your original code here>
long startTime = System.currentTimeMillis();
do
{
//stuff
} while (System.currentTimeMillis() - startTime < 1000*60*60);
try the following:
long startTime = System.currentTimeMillis();
long endTime = startTime + (60*60*1000);
while(System.currentTimeMillis() <= endTime) {
Command nextCommand = getNextCommandToExecute();
}
One drawback with this method is if the Command you are trying to execute runs past the 60 minute timer or never finishes at all. If this behavior is not allowed, you are better off implementing a thread that interrupts whatever thread is running this loop.
long startTime = System.currentTimeMillis();
do{
Command nextCommand = getNextCommandToExecute();
}while (startTime < startTime+60*60*1000);
You could use:
long startTime = System.nanoTime();
do {
Command nextCommand = getNextCommandToExecute();
} while ((System.nanoTime() - startTime) < 60 * 60 * 1000000000L);
Please note System.nanoTime() is slightly different from using System.currentTimeMillis() not only in the scale, but also in what it measures: System.nanoTime() is the elapsed time, and System.currentTimeMillis() is the system time (wall clock). If the system time changes, System.currentTimeMillis() doesn't work as expected. (This doesn't apply to summertime change however, as the returned value is UTC / GMT.)
1000000000L nanoseconds is one second. Please note the L for long. In Java 7 you could also write the more readable 1_000_000_000L.
Related
I want to calculate the total running time of my program from start to end and refresh running time in JFrame, but when I run my program I get excess 70 years, 1 day and 2 hours. Why ? What wrong ?
private void setMachineTime(){
Timer timer = new Timer();
long startTime = new Date().getTime();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
long endTime = new Date().getTime();
long diffTime = endTime - startTime ;
String time = new SimpleDateFormat("yy:mm:dd:HH:mm:ss").format(diffTime);
System.out.println(time);
}
}, 0, 1000);
}
actual result
UPD:
I rewrote code with my own format time method. Now I got what I want. Thanks to all of you.
private void setMachineTime(){
Timer timer = new Timer();
long startTime = new Date().getTime();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
long endTime = new Date().getTime();
long diffTime = endTime - startTime;
String diffSeconds = formatTime(diffTime / 1000 % 60);
String diffMinutes = formatTime(diffTime / (60 * 1000) % 60);
String diffHours = formatTime(diffTime / (60 * 60 * 1000) % 24);
System.out.println(diffHours + ":" + diffMinutes + ":" + diffSeconds);
}
}, 0, 1000);
}
private String formatTime(long diff){
long t;
t = diff;
if(t < 10){
return String.valueOf("0"+t);
} else {
return String.valueOf(t);
}
}
You are formatting the time difference as yy:mm:dd:HH:mm:ss. Just printing out diffTime would give you the milliseconds, divide by 1000 if you need seconds.
EDIT: I think i see what you are trying to do, but you are dealing with a time interval, which cannot be formatted as a date. You'll need to roll your own formatting for displaying the time as seconds, minutes, hours etc. or use an external library.
getTime return number of milliseconds from 1.1.1970...and same is for SimpleDateFormat converting number to date (and then formating it). It means when your diffTime = 0, SimpleDateFormat will try to format Date 1.1.1970 0:00:00 and with your formating string it will be 70:01:01:00:00:00. Try to use http://joda-time.sourceforge.net/api-release/org/joda/time/Interval.html instead.
And by the way, your formating string is wrong anyway...you use mm where I supouse you wanted month...but mm are minutes.
I am creating a program that makes a calculation every minute. I don't know exactly how to do this efficiently, but this is some pseudo code I have written so far:
stockCalcTimerH = System.currentTimeMillis() - 1;
stockCalcTimerI = stockCalcTimerH;
stockCalcTimer = System.currentTimeMillis();
if (stockCalcTimerI < stockCalcTimer) {
*do calcuations*
stockCalcTimerI + 60000;
When I print both values out on the screen, it comes out as this:
stockCalcTimerI = 1395951070595
stockCalcTimer = 1395951010596
It only subtracts the number, and doesn't add the 60000 milliseconds...
I'm kind of new to Java, but any feedback helps.
Thanks for reading!!
stockCalcTimerI + 60000;
The new value never gets assigned to a variable.
Change that to:
stockCalcTimerI += 60000;
Which is the same as
stockCalcTimerI = stockCalcTimerI + 60000;
You can use java.util.Timer class to schedule runs.
TimerTask task = new TimerTask() {
#Override public void run() {
// do calculations
}
};
int delay = 0; // no delay, execute immediately
int interval = 60*1000; // every minute
new Timer().scheduleAtFixedRate(task, delay, interval);
Below is My code:
public class FindTime {
HashSet<String> hashSet = new HashSet<>();
long m1() {
hashSet.add("hai");
hashSet.add("me");
hashSet.add("you ");
hashSet.add("I");
hashSet.add("Us");
Iterator it = hashSet.iterator();
long startTime = System.currentTimeMillis();
while (it.hasNext()) {
System.out.println(it.next());
}
return startTime;
}
public static void main(String[] args) {
FindTime ft = new FindTime();
long startTime = ft.m1();
System.out.println("startTime" + startTime);
long endTime = System.currentTimeMillis();
System.out.println("End time" + endTime);
System.out.println("d/W" + (endTime - startTime));
}
}
I don't know is that one is correct way or not.My requirement is
"I want to calculate time taken to Iterate a HashSet".
To be more precise use System.nanoTime()
public class FindTime {
HashSet<String> hashSet = new HashSet<>();
long m1()
{
hashSet.add("hai");
hashSet.add("me");
hashSet.add("you ");
hashSet.add("I");
hashSet.add("Us");
Iterator it = hashSet.iterator();
long startTime = System.nanoTime();
while (it.hasNext()) {
System.out.println(it.next());
}
return startTime;
}
public static void main(String[] args) {
FindTime ft = new FindTime();
long startTime = ft.m1();
long endTime = System.nanoTime(); //CALCULATE THE END TIME BEFORE PRINTING START TIME
//BECAUSE PRINT OPERATION WILL ALSO TAKE TIME THAT WILL BE ADDED TO DIFFERENCE
System.out.println("Start time in nano seconds" + startTime); //No need because you actually need difference
System.out.println("End time in nano seconds" + endTime);
System.out.println("Difference in Nano Seconds" + (endTime - startTime));
//long microsecondsTime = (end - start) / 1000; //If you need in microseconds
}
}
Your code is correct. You've calculated the time which taken for iterating and printing the output in console. Print may take more time than iteration.
You may have also returned the execution time by
return System.currentTimeMillis()- startTime;
See Also : Do not use System.out.println in server side code
As you telling you need time to take only for iterate not for insertion then you can use it like
long m1() {
hashSet.add("hai");
hashSet.add("me");
hashSet.add("you ");
hashSet.add("I");
hashSet.add("Us");
Iterator it = hashSet.iterator();
long startTime = System.nanoTime();
while (it.hasNext()) {
System.out.println(it.next());
}
long endTime = System.nanoTime();
System.out.println("time taken in nano seconds" + endTime-startTime);
return endTime-startTime;
}
reason is if you take time into your main function then it will also calculate the time for insertion.
Yes I am agree that it will not affect too much but we know that is not right thing to do.Even here I am printing so here also it will add the printing time that is not exactly correct.
I am working in a Java project and we are not using any profiling tool.
Is there a way to find out the time a method takes for execution without using any profiling tool?
Why dont you use something like:
int startTime = System.currentTimeMillis();
methodCall();
int endTime = System.currentTimeMillis();
int totalTime = endTime - startTime;
System.out.println("Time to complete: " + totalTime);
Then you could add the /1000 or whatever to format the time as you desire.
Catch System.currentTimeMillis() before start and at the end minus with System.currentTimeMillis().
You will be able to know how much time your method takes to execute.
void fun(){
long sTime=System.currentTimeMillis();
...
System.out.println("Time Taken to execute-"+System.currentTimeMillis()-sTime+" milis");
}
Here is a sample program to capture timings:
package com.quicklyjava;
public class Main {
/**
* #param args
* #throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
// start time
long time = System.nanoTime();
for (int i = 0; i < 5; i++) {
System.out.println("Sleeping Zzzz... " + i);
Thread.sleep(1000);
}
long difference = System.nanoTime() - time;
System.out.println("It took " + difference + " nano seconds to finish");
}
}
And here is the output:
Sleeping Zzzz... 0
Sleeping Zzzz... 1
Sleeping Zzzz... 2
Sleeping Zzzz... 3
Sleeping Zzzz... 4
It took 5007507169 nano seconds to finish
I would like to write a test for a method, that calls observers in a specific intervall, so that they will execute a method. The timer-object runs in its own thread.
Method of timer to be tested
private long waitTime;
public Metronome(int bpm) {
this.bpm = bpm;
this.waitTime = calculateWaitTime();
this.running = false;
}
public void run() {
long startTime = 0, estimatedTime = 0, threadSleepTime = 0;
running = true;
while (running) {
startTime = System.nanoTime();
tick();// notify observers here
estimatedTime = System.nanoTime() - startTime;
threadSleepTime = waitTime -estimatedTime;
threadSleepTime = threadSleepTime < 0 ? 0 : threadSleepTime;
try {
Thread.sleep(threadSleepTime / 1000000l);
} catch (InterruptedException e) {
// sth went wrong
}
}
}
Snippet from my testclass
private int ticks;
private long startTime;
private long stopTime;
#Test
public void tickTest(){
metronome.setBpm(600);
startTime = System.nanoTime();
metronome.run();
long duration = stopTime - startTime;
long lowThreshold = 800000000;
long highThreshold = 900000000;
System.out.println(duration);
assertTrue(lowThreshold < duration);
assertTrue(duration <= highThreshold);
}
#Override
public void update(Observable o, Object arg) {
ticks ++;
if(ticks == 10){
metronome.stop();
stopTime = System.nanoTime();
}
}
Right now, my testclass registers as an observer at the object in question, so that i can count the number of times tick() was executed. The test measures the time before and after the execution, but it feels awkward to me, to test the behaviour this way.
Any suggestions for improving the test?
Sometimes the solution is to use something from a standard library that is sufficiently simple such that it does not need to be tested. I think SchedulerExecuterService will do the trick for replacing the home made Timer being tested here. Note that it is pretty rare to be bit by a bug in library code, but they do exist.
In general though, I think it is okay to create a helper class or use a mocking framework (Mockito) to do something simple like counting "ticks".
P.S. You can replace Thread.sleep(threadSleepTime / 1000000l) with TimeUnit.NANOSECONDS.sleep(threadSleepTime) ... which moves some logic from your code into the standard library.
Based on your comments I changed my code. Instead of implementing the Observer-interface in my testclass, I now created a private class, that implements the interface an registers at my timer.
Thanks for your time and thoughts.
Here is what the code now looks like:
revised testcode
#Test(timeout = 2000)
public void tickTest(){
long lowThreshold = 400000000;
long highThreshold = 600000000;
TickCounter counter = new TickCounter();
metronome.addObserver(counter);
metronome.setBpm(600);
startTime = System.nanoTime();
metronome.run();
long duration = System.nanoTime() - startTime;
assertTrue(lowThreshold <= duration);
assertTrue(duration <= highThreshold);
}
private class TickCounter implements Observer{
private int ticks;
public TickCounter(){
ticks = 0;
}
#Override
public void update(Observable o, Object arg) {
ticks++;
if(ticks == 5){
metronome.stop();
}
}
}
snippet from my revised timer
private long expectedTime; // calculated when bpm of timer is set
#Override
public void run() {
long startTime = 0, elapsedTime = 0, threadSleepTime = 0;
running = true;
while (running) {
startTime = System.nanoTime();
tick();
elapsedTime = System.nanoTime() - startTime;
threadSleepTime = expectedTime - elapsedTime;
threadSleepTime = threadSleepTime < 0 ? 0 : threadSleepTime;
try { TimeUnit.NANOSECONDS.sleep(threadSleepTime); } catch (Exception e) { }
}
}
My biggest issue might have been, that I implemented the observer-interface in my JUnit testcase. So I created a private observer, that specifically counts the number of times, the tick was executed. The counter then stops my timer.
The testmethod measures the timing and asserts, that the needed time is somewhere between my defined limits.
It depends on how accurately you need to measure the time.
If you feel that it's "awkward" is that because you're not sure that the measurement is accurate enough? Do you fear that the OS is getting in the way with overhead?
If so, you may need an external timing board that's synchronized to an accurate source (GPS, atomic standard, etc.) to either test your code, or possibly to provide the trigger for your firing event.
Try this. You also need the time you are expecting. The expected time will be 1000000000/n where n is the number of times your timer needs to tick() per second.
public void run(){
long time = System.nanotime();
long elapsedTime = 0;
// Hope you need to tick 30 times per second
long expectedTime = 1000000000/30;
long waitTime = 0;
while (running){
tick();
elapsedTime = System.nanotime()-time;
waitTime = expectedTime-elapsedTime();
if (waitTime>0){
try { Thread.sleep(waitTime) } catch (Exception e){}
}
time = System.nanotime();
}
}