JavaFX - Using time as a variable for a line chart - java

I am essentially trying to create a visual representation of the memory being used in my program. I have created a LineChart and set the Y-axis to be Memory used, and the X-axis to be time. My question is, what is the best way to set up a timer, so that incoming data about memory usage can be paired with the current time.
By this I mean, I want to start a timer when the window displays, and continue to count up (possibly with millisecond precision), and so I can say that after the program has been running for this long, this is the amount of memory used.
What would be the best resources to use for this task?

The best bet would probably just to use System.currentTimeMillis(); and set it to a variable when you start the count, then call it again and compare the saved value with the new timer to get your time.
so..
Long startTime = System.currentTimeMillis();
//Do whatever stuff
long timeElapsed = System.currentTimeMillis() - startTime;
One thing to keep in mind with this though, is currentTimeMillis() is platform dependent on how granular it is. On unix-based you get 1 ms. of a granularity minimum, I think on windows it's 50. So if you need something more accurate than 50 ms. time steps, you might need a different method.

You must use a StopWatch to measure the time. Please go through the following links
https://stackoverflow.com/a/8255766/1759128
There are many alternatives in different answers of the question. You can use any of them !

Related

Delay by 1 millisecond not working?

I am trying to generate a number using:
System.currentTimeMillis()
I have to generate these numbers sometimes 5 times in a row, which happens so fast that they are the same (but I don't want them to be the same as we are using them as part of a unique field)
I thought I could put a delay in between when each one is generated, which would prevent them from being the same, using:
TimeUnit.MILLISECONDS.sleep(1);
But this still generates the same number. It only seems to generate a new one if I increase it to about 60 and above. I am trying to understand why this is? Thanks
If you want to generate 5 numbers starting at the current time that aren't the same - which as far as I can tell is your only requirement - you can use
long t = System.currentTimeMillis();
long ts[] = { t, t+1, t+2, t+3, t+4 };
Thread.sleep is absurd here. The user (or whoever) should not experience a delay for something that can be computed now.
The Java docs for Thread.sleep() says:
Causes the currently executing thread to sleep (temporarily cease execution) for the
specified number of milliseconds, subject to the precision and accuracy of system
timers and schedulers.
That bit about the "precision and accuracy of system timers and schedulers" is pretty important. I'd say that's why your not getting anything until you use Thread.sleep(60): those system timers just aren't very accurate.
Now a better question is why are you trying to "generate numbers..."
The JavaDoc for System.currentTimeMillis() says:
"Note that while the unit of time of the return value is a millisecond,
the granularity of the value depends on the underlying operating system
and may be larger. For example, many operating systems measure time in
units of tens of milliseconds."
From this, is it likely that your problem is not java - related, but rather your operating system is not keeping the time per - millisecond.
Thread.sleep guarantees the Thread will sleep, but not for how long. It will definitely sleep, at least for 1 millisecond but your os may not give priority to jvm, or jvm may not give priority to the thread after 1 millisecond.

How do I measure how long the program is executed

I am creating a Java Application where the OS's System Clock is adjusted from time to time. (so it's like a peer-to-peer NTP experiment)
I am looking for a Java construct that is something like a virtual clock where in I can still get the age of the application in milliseconds from the time it was executed. Because if I will always just use System.currentTimeMillis(), it might give me false age of the application.
Is there something like that? without actually creating another thread solely for it?
To calculte the elapsed time of your program you have multiple possibilities. Not all will fit your program because your system time could be change while your program is running.
currentTimeMillis()
With that method you get the current time of your system in millisecounds. If you want to calculate the runnning time of your program you could save the currentTime in a long variable. When you want the time the program is needed, you just simply subtract the currentTime now with your saved one.
Save the time when your program starts!
long start = System.currentTimeMillis();
Subtract the end time and the start time!
long need = System.currentTimeMillis() - start;
Keep in mind that if you change the system time you get a wrong time!
nanoTime()
With nanoTime you get the elapsed time of your Virtual Java Machine in nanosecounds. If you want to calculate the elapsed time, you have to do the same like with currentTimeMillis(). At the beginning you save the time and at the end you substract it.
Save the time when your program starts!
long start = System.nanoTime();
Subtract the end time and the start time!
long need = (System.nanoTime() - start) / 1000000; // divide to get millisecounds
Keep in mind that you get the right time, even if you change the system time, because you use the time of the Virtual Java Machine!
Difference
You only get the right elapsed time with System.nanoTime(). You should not use System.currentTimeMillis(), unless you do not mind that your result is wrong. currentTimeMillis() is to measure "wall-clock" time. When your system time is updateing, you simply get a wrong time. nanoTime() is actully mad for that, that you calculate the elapsed time.
No way to do this directly in Java, the only solution to this is to record the time differences applied to the system clock and takes this into account in your application.
Of course this depends greatly on the underlying operating system and the tools used to adjust the system clock.

java stop watch program - using System.nanoTime() and TimerTask together

I am writing a mini program in Java to use as a stop watch but I am not sure if I am using the right methods in terms of efficiency and accuracy.
From what I have read on stackoverflow it it appears that System.nanoTime() is the best method to use when measuring time elapsed. Is that right? To what extent is it accurate as in to the nearest nanosecond, microsecond, millisecond etc.
Also, while my stop watch is running, I would like it to display the current time elapsed every second. To do this I plan to use a TimerTask and schedule it to report the time (converted to seconds) every second.
Is this the best way? Will this have any effect on the accuracy?
Lastly with my current design will this use up much of a computer's resources e.g. processing time.
PS Sorry can't share much code right now cause I've just started designing it. I just did not want to waste time on a design that would be inefficient and make an inaccurate timer.
Yes, you can use java.util.Timer and TimerTask that runs periodically and updates your view every second. However I do not think you have to deal with nono seconds while you actually need resolution of seconds only. Use regular System.currentTimeMillis().

java.util.Timer - inconsistent speed between events?

I am using java.util.timer for a game that I am programming to increment the location of a JLabel but it usually goes much slower than I need it to. Sometimes it goes the correct speed but then for no reason the next time I execute the program it will be slow again. I used the following code for the timer.
java.util.Timer bulletTimer= new java.util.Timer();
bulletTimer.schedule(new bulletTimerTask(), 0, 2);
I also tried javax.swing.timer and had the same problem. Any help would be appreciated.
edit: it works fine with another timer where I set the delay to 2000 ms
Since you are moving a JLabel, I would actually continue to use (a single) swing.Timer. The reason for this is that the callback will always happen "on the EDT" and thus it is okay to access Swing components. (If you are using util.Timer then the update should be posted/queued to the EDT, but this is a little more involved.)
Now, bear in mind that util.Timer and swing.Timer do not have guaranteed timings (other than "will be at least X long") and, to this end, it is important to account for the "time delta" (how long since it was since the last time the update occurred).
This is discussed in the article Fix Your Timestep! While the article was written about a simple game-loop and not a timer, the same concept applies. To get a consistent update pattern for a fixed velocity (no acceleration), simply use:
distance_for_dt = speed * delta_time
new_position = old_position + distance_for_dt
This will account for various fluctuations on a given system -- different system load, process contention, CPU power throttle, moon phase, etc. -- as well as make the speed consistent across different computers.
Once you are familiar with the basic position update, more "advanced" discrete formulas can be used for even more accurate positioning, including those that take acceleration into account.
Happy coding.
As BizzyDizzy poined out, System.nanoTime can be used to compute the time-delta. (There are a few subtle issues with System.currentTimeMillis and clock changes.)
You can use System.nanoTime() which came with Java 5 and it is the most high resolution timer in Java. It provides value in nanoseconds.

How to get time delta independently from system time?

I'm writing a simple timer in Java. It has Start and Stop buttons, along with a text view showing how much time has passed since the timer was started.
It's implemented by setting initial time with System.currentTimeMillis() and updating current value each second in a loop.
The problem is that if I change system time while the timer is running, the whole measurement fails. E.g., if I set time back one month, the timer shows negative value as currentTimeMillis() now returns less value than initial.
So, how do I calculate time delta which would be independent from the system time? It would be also great to make this solution cross-platform.
Use:
System.nanoTime()
This should do it. It doesn't take the system time into account, and can only be used to measure elapsed time. Which is what you want. You need to divide by 1 million to get the elapsed milliseconds. See also the Javadocs.
System.nanoTime();
From Javadoc:
This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.
Use time web services . for example this or this or this
You can install demon like NTP, system time jumping in any directions has a lot of issues and can lead to quite a lot of other problems.
System.nanoTime() not necessarily depend on the system clock - but it can - just make sure the system time is correctly progressing.
Modifying system time is a privileged operation, so it someone does that they shall know better.
Here is a bug 13 years of age regarding the same case: http://bugs.sun.com/view_bug.do?bug_id=4290274
HTH

Categories

Resources