Timing program in java

Make a simple timer in Java

I can’t seem to figure out how to make a simple timer in java. All I need it to do is just display time, really. So just a start method, and it keeps counting up like 0:00, 0:01, 0:02, etc. I’ve seen some other similar forum posts on this, but all the code is kind of complicated for my level of understanding; I’m kind of new to java. But it shouldnt be that hard to make a timer that just performs such a basic function? If anyone could help it would be greatly appreciated 🙂

A timer with a display would involve threading. If you’re new to Java, and perhaps programming in general, I recommend learning simpler stuff first before diving into threading.

Such a timer does not necessarily involve threading. If you already have an event loop, that same existing loop can be used. If the program is a command line teletype style program, then the foreground (main) thread could work sufficiently. And, if you have a GUI program, you need only assure that the screen gets refreshed more often than the user looks at, and that might be done using a GUI timer capability. You should not assume that threading is needed.

5 Answers 5

This is not difficult. However, I would caution you that I have seen some very confused answers on stack overflow, in some cases shockingly poor coding habits, so be very careful. First let me answer the question.

If seem that the biggest mistake that programmers make in implementing a timer, is thinking that they need something to keep track of the current time. That is, they write some sort of loop that increments a variable every second or some such silly thing. You do not need to write code to keep track of the time. The function System.currentTimeMillis() will do that for you, and it does it quite accurately.

Timer code will involve two aspects which many programmers mix up:

All you need to do to calculate the time to display, is to record the time that the timer started:

long startTime = System.currentTimeMillis(); 

Later, when you want to display the amount of time, you just subtract this from the current time.

long elapsedTime = System.currentTimeMillis() - startTime; long elapsedSeconds = elapsedTime / 1000; long secondsDisplay = elapsedSeconds % 60; long elapsedMinutes = elapsedSeconds / 60; //put here code to format and display the values 

The biggest mistake that programmers make is to think they need a variable to hold the current time and then to write code to increment that variable every second, e.g. something called «elapsedSeconds» which they maintain. The problem is that you can schedule code to be called every second, but there is no guarantee of exactly when that code will be called. If the system is busy, that code might be called quite a bit later than the second. If the system is extremely busy (for example page fetching from a faulty disk) it could actually be several seconds late. Code that uses the Thread.sleep(1000) function to loop every second will find that the error builds up over time. If sleep returns 300ms late one time, that error is compounded into your calculation of what time it is. This is all completely unnecessary because the OS has a function to tell you the current time.

The above calculation will be accurate whether you run this code every second, 100 times a second, or once every 3.572 seconds. The point is that currentTimeMillis() is the accurate representation of the time regardless of when this code is called — and that is an important consideration because thread and timer events are not guaranteed to be accurate at a specific time.

Читайте также:  Настроить php ini на сервере

The second aspect of a timer is refresh of the display. This will depend upon the technology you are using to display with. In a GUI environment you need to schedule paint events. You would like these paint events to come right after the time that the display is expected to change. However, it is tricky. You can request a paint event, but there may be hundreds of other paint events queued up to be handled before yours.

One lazy way to do this is to schedule 10 paint events per second. Because the calculation of the time does not depend on the code being called at a particular point in time, and because it does not matter if you re-paint the screen with the same time, this approach more or less guarantees that the displayed time will show the right time within about 1/10 of a second. This seems a bit of a waste, because 9 times out of 10 you are painting what is already on the screen.

If you are writing a program with animation of some sort (like a game) which is refreshing the screen 30 times a second, then you need do nothing. Just incorporate the timer display call into your regular screen refresh.

If paint events are expensive, or if you are writing a program that does terminal-style output, you can optimize the scheduling of events by calculating the amount of time remaining until the display will change:

long elapsedTime = System.currentTimeMillis() - startTime; long timeTillNextDisplayChange = 1000 - (elapsedTime % 1000); 

The variable timeTillNextDisplayChange holds the number of milliseconds you need to wait until the seconds part of the timer will change. You can then schedule a paint event to occur at that time, possibly calling Thread.sleep(timeTillNextDisplayChange) and after the sleep do the output. If your code is running in a browser, you can use this technique to update the page DOM at the right time.

Note, that there is nothing in this calculation of the display refresh that effects the accuracy of the timer itself. The thread might return from sleep 10ms late, or even 500ms late, and the accuracy of the timer will not be effected. On every pass we calculate the time to wait from the currentTimeMillis, so being called late on one occasion will not cause later displays to be late.

That is the key to an accurate timer. Do not expect the OS to call your routine or send the paint event exactly when you ask it to. Usually, of course, with modern machines, the OS is remarkably responsive and accurate. This happens in test situations where you are not running much else, and the timer seems to work. But, in production, under rare stress situation, you do not want your timer «drifting» because the system is busy.

Читайте также:  Скорость выполнения кода java

Источник

How do I make a delay in Java?

I am trying to do something in Java and I need something to wait / delay for an amount of seconds in a while loop.

while (true) < if (i == 3) < i = 0; >ceva[i].setSelected(true); // I need to wait here ceva[i].setSelected(false); // I need to wait here i++; > 

What is the purpose of waiting? Are you waiting for a certain event to happen? Make sure you understand what sleep() method does

8 Answers 8

If you want to pause then use java.util.concurrent.TimeUnit :

To sleep for one second or

As this is a loop, this presents an inherent problem — drift. Every time you run code and then sleep you will be drifting a little bit from running, say, every second. If this is an issue then don’t use sleep .

Further, sleep isn’t very flexible when it comes to control.

For running a task every second or at a one second delay I would strongly recommend a ScheduledExecutorService and either scheduleAtFixedRate or scheduleWithFixedDelay .

For example, to run the method myTask every second (Java 8):

public static void main(String[] args) < final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); executorService.scheduleAtFixedRate(App::myTask, 0, 1, TimeUnit.SECONDS); >private static void myTask()
public static void main(String[] args) < final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); executorService.scheduleAtFixedRate(new Runnable() < @Override public void run() < myTask(); >>, 0, 1, TimeUnit.SECONDS); > private static void myTask()

Источник

How to set a Timer in Java?

How to set a Timer, say for 2 minutes, to try to connect to a Database then throw exception if there is any issue in connection?

Coul the OP clarify if they desire to simple attempt the action for at least 2 minutes, or if the exception must be thrown now later the two minutes, even if an attempt to connect is currently under way

5 Answers 5

So the first part of the answer is how to do what the subject asks as this was how I initially interpreted it and a few people seemed to find helpful. The question was since clarified and I’ve extended the answer to address that.

Setting a timer

First you need to create a Timer (I’m using the java.util version here):

To run the task once you would do:

timer.schedule(new TimerTask() < @Override public void run() < // Your database code here >>, 2*60*1000); // Since Java-8 timer.schedule(() -> /* your database code here */, 2*60*1000); 

To have the task repeat after the duration you would do:

timer.scheduleAtFixedRate(new TimerTask() < @Override public void run() < // Your database code here >>, 2*60*1000, 2*60*1000); // Since Java-8 timer.scheduleAtFixedRate(() -> /* your database code here */, 2*60*1000, 2*60*1000); 

Making a task timeout

To specifically do what the clarified question asks, that is attempting to perform a task for a given period of time, you could do the following:

ExecutorService service = Executors.newSingleThreadExecutor(); try < Runnable r = new Runnable() < @Override public void run() < // Database task >>; Future f = service.submit(r); f.get(2, TimeUnit.MINUTES); // attempt the task for two minutes > catch (final InterruptedException e) < // The thread was interrupted during sleep, wait or join >catch (final TimeoutException e) < // Took too long! >catch (final ExecutionException e) < // An exception from within the Runnable task >finally

This will execute normally with exceptions if the task completes within 2 minutes. If it runs longer than that, the TimeoutException will be throw.

Читайте также:  Split on tab python

One issue is that although you’ll get a TimeoutException after the two minutes, the task will actually continue to run, although presumably a database or network connection will eventually time out and throw an exception in the thread. But be aware it could consume resources until that happens.

Источник

How to time Java program execution speed

How do you time the execution of a java program? I’m not sure what class I should use to do this. I’m kinda looking for something like:

// Some timer starts here for (int i = 0; i < length; i++) < // Do something >// End timer here System.out.println("Total execution time: " + totalExecutionTime); 

14 Answers 14

final long startTime = System.currentTimeMillis(); for (int i = 0; i < length; i++) < // Do something >final long endTime = System.currentTimeMillis(); System.out.println("Total execution time: " + (endTime - startTime)); 

Is there some particular reason you used «final» here? What would be different if you dropped that keyword?

@dijxtra using final has the advantage that you can’t accidentally assign to it (as well as other advantages, such as anonymous class access, etc.). In this code it wouldn’t make a difference. It’s a fairly common practice to make everything final and only un- final ize it if you need to.

The code to be tested, along with the time measurements, should be run multiple times and the first result should be discarded. The first will likely include class loading times etc. By running it multiples times also of course you get an average which is more helpful and reliable.

Be aware that there are some issues where System#nanoTime() cannot be reliably used on multi-core CPU’s to record elapsed time . each core has maintains its own TSC (Time Stamp Counter): this counter is used to obtain the nano time (really it is the number of ticks since the CPU booted).

Hence, unless the OS does some TSC time warping to keep the cores in sync, then if a thread gets scheduled on one core when the initial time reading is taken, then switched to a different core, the relative time can sporadically appear to jump backwards and forwards.

I observed this some time ago on AMD/Solaris where elapsed times between two timing points were sometimes coming back as either negative values or unexpectedly large positive numbers. There was a Solaris kernel patch and a BIOS setting required to force the AMD PowerNow! off, which appeared to solved it.

Also, there is (AFAIK) a so-far unfixed bug when using java System#nanoTime() in a VirtualBox environment; causing all sorts of bizarre intermittent threading problems for us as much of the java.util.concurrency package relies on nano time.

Источник

Оцените статью