Java 11 get current Microseconds? - java

I already read an answer about if it's possible in Java 8 to get the current microseconds and the answer was no, but is it possible now in Java11?
The solution by using System.nanoTime() * 1000 is too inefficient.
Note: The Goal is NOT to get the exact current time in nanoseconds (for example 12:00 PM), obviously that's not working like this.
I would appreciate any help :)

As before, Instant.now() uses the most accurate time source available to the system. Depending on the system, there may not be anything finer-grained than System.currentTimeMillis.
As mentioned in the comments, System.nanoTime() / 1000 can be used for measuring the time between values, but doesn't give you anything like "the current time" -- you can't tell from it, for example, whether or not it's 3:00 PM.
If you need to measure or calculate e.g. the time between events in your program, there is nothing that will do better for you than System.nanoTime.

The Answer by Wasserman is correct. Here are more thoughts.
Not real-time
You commented:
When you try to do a very exact scheduler
Conventional implementations of Java, and conventional computer hardware, are not “very exact” along the scale of nanosecond and microsecond that you seemed to be targeting.
For “very exact” scheduling, you would have to use special hardware with special software. Look for the buzzword real-time, such as real-time Java.
System.nanoTime()
You said:
The solution by using System.nanoTime() * 1000 is too inefficient. Note: The Goal is NOT to get the exact time in nanoseconds
Be aware that System.nanoTime() does not tell you the current time.
System.nanoTime() tells you the approximate amount of nanoseconds that have elapsed since some arbitrarily chosen moment. In some implementations of Java, that moment may have been when the JVM was launched, or when the computer was booted, or something else. But you cannot count on that origin, nor should you care about the origin.
Represent elapsed time using Duration class.
To capture elapsed time in Java for micro-benchmarking:
long start = System.nanoTime() ;
…
Duration elapsed = Duration.between( start , System.nanoTime() ) ;
You can interrogate the Duration for its parts such as nanoseconds, whole seconds, minutes, and hours.
You said:
System.nanoTime() * 1000 is too inefficient
You must have meant:
( start - System.nanoTime() ) / 1_000
… to get a count of elapsed microseconds.
And, no, dividing or multiplying integers is not “inefficient“. If you care about optimizing for integer division operations, you should not be using conventional Java on conventional hardware, as discussed in section above.
Instant.now()
If you want to capture elapsed time as seen by human clocks:
Instant start = Instant.now() ; // May be precise to milliseconds, microseconds, or such depending on your implementation of Java and your host computer hardware clock.
…
Instant end = Instant.now() ;
To represent that elapsed time unattached to the timeline, use Duration.
Duration elapsed = Duration.between( start , end ) ;
To represent that elapsed time attached to the timeline, write a class storing a pair of Instant objects.
record SpanOfTime ( Instant start , Instant end ) {}
Or better yet, add the ThreeTen-Extra library to your project. This library brings classes that add functionality to the built-in java.time classes. One of these is Interval, with handy comparison methods such as abuts, contains, encloses, overlaps, etc.

Related

Difference B/W Clock.systemUTC() And System.currentTimeMillis()

Clock.systemUTC() docs say that this method may use System.currentTimeMillis() or a higher resolution clock if available. What clock does System.currentTimeMillis() use then? Can there be a difference in the granularity of these two values?
Can there be a difference in the granularity of these two values?
The Clock class has 2 methods for retrieving the current time:
millis()
instant()
Since instant() returns an Instant, which can represent time with a precision of nano-seconds, the answer is obvious.
Answer: Yes.
What clock does System.currentTimeMillis() use then?
If you look at the source code of Clock.systemUTC(), you will find that it uses an internal SystemClock class. In a comment in the millis() method, it says (quoting Java 15):
System.currentTimeMillis() and VM.getNanoTimeAdjustment(offset)
use the same time source - System.currentTimeMillis() simply
limits the resolution to milliseconds.
So we take the faster path and call System.currentTimeMillis()
directly - in order to avoid the performance penalty of
VM.getNanoTimeAdjustment(offset) which is less efficient.
Answer: System.currentTimeMillis() and Clock.instant() use the same time source.

How do I calculate actions done per minute with Java? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm writting a own application to help RuneScape 3 streamers educate their viewers with a DPS Rotation showing, and i'm wanting to implement a feature A.K.A APM (Which means Actions per minute) which is in other words, number of Keys (hotkeys) pressed within a minute, what i'm doing atm is, having a LocalTime when the thread starts, and every 5 secs it should show APM, but I guess my formula isn't correct.
Current formula is:
LocalTime apm = Main.keysPressed.size() / (LocalTime.now().minus(Main.apmLocalTime);
Which is:
counter / (current_time - start_time)
Problem is, the .minus() asks for a TemporalUnit as parameter, and i'm quite lost.
Can someone plz help me getting the formula.
tl;dr
actionsCount / Duration.between( start , Instant.now() ).toMinutes()
java.time.Instant
Use Instant to track a moment, not LocalTime.
Instant represents a moment, a point on the timeline, as seen in UTC. The class resolves to nanoseconds, but current conventional hardware clocks limit capturing the current moment to microseconds or milliseconds.
The LocalTime class represents merely a time-of-day without the context of a date and time zone or offset-from-UTC. So this class cannot represent a moment.
Use Duration class for ease, and to make your code more self-documenting.
Instant start = Instant.now() ;
…
Duration elapsed = Duration.between( start , Instant.now() ) ;
long minutesElapsed = elapsed.toMinutes() ; // Get a count of whole minutes in total span of time.
long actionsPerMinute = ( actionsCount / minutesElapsed ) ;
Tip: While generally in Java we want to use the more general interfaces and superclasses rather than the more specific concrete classes, in java.time the opposite is true. In java.time we want to use the specific concrete classes, because the framework programmers told us so in the documentation. So if your IDE or compiler suggests a Temporal, for example, follow the Javadoc to see the list of implementing classes, such as Instant.

Calculate a cost for every 15-minute chunk of time elapsed so far

I want the user to be able to get updates on the cost for the time elapsed for the use of an app. Every 15-minute chunk of time elapsed so far is priced at 10 units of currency.
I care only about elapsed time. Aligning with the quarters of the hour (minutes 0-15, 15-30, 30-45, 45-0) is not a goal.
For example, at the beginning, the cost is 0 units. Five minutes later, still 0 units. After 17 minutes, 20 units is the current cost ( 10 units of currency * a single 15-minute block of time completed). After 33 minutes, 20 units is the current cost, as 2 chunks of 15-minutes each have elapsed so far.
The last current chunk of time under 15-minutes is ignored. No pro rata.
tl;dr
Duration // Represent a span-of-time not attached to the timeline. Internally, this class stores a number of whole seconds plus a fractional second as a count of nanoseconds.
.between( // Calculate elapsed time.
start , // Starting moment captured a while ago using `Instant.now()` call.
Instant.now() // Capture the current moment.
) // Returns a `Duration` object.
.dividedBy( // Get whole number (ignoring remainder) of number of 15-minute chunks occurred within that previous `Duration`.
Duration.ofMinutes( 15 ) // Another `Duration` object, our 15-minute chunk definition.
) // Returns a `long`, a 64-bit integer.
* // Multiply our number of chunks of 15-minutes by the price-per-chunk.
price
Details
Use only classes from the java.time packages, defined in JSR 310. Avoid terrible legacy date-time classes (Date, Calendar).
Capture the starting moment. Use Instant class, to represent a moment in UTC, with a resolution as fine as nanoseconds.
Instant start = Instant.now() ;
Write a method to calculate your cost for elapsed time. In this method:
First we get elapsed time, the amount of time from the starting moment to the current moment. We do this in UTC, as there is no benefit to involving a time zone. We represent elapsed time as a Duration.
Second, we count completed chunks of elapsed time. We define the chunk of time for which we are charging, 15 minutes, using the Duration class again. Then we call Duration::dividedBy to get a count of completed chunks.
Third, we calculate cost by multiplying the unit price times the whole number of chunks of time elapsed. If you are using a fractional number for currency, such as US or Canadian dollars, rather than an integer number, use BigDecimal rather than Integer. Search Stack Overflow for more info, as this has been covered many times already.
Note the use of Math.toIntExact to truncate from a 64-bit long to a 32-bit int but throwing an exception if overflow occurs.
Code.
public Integer calculateCostForElapsedTimeSoFar ( final Instant start , final Integer price )
{
// Determine elapsed time.
Instant now = Instant.now();
Duration elapsed = Duration.between( start , now );
// See how many chunks of 15 minutes have occurred.
Duration chunk = Duration.ofMinutes( 15 ); // Charge for every chunk of time in chunks of 15 minutes. You could make this a constant instead of a local variable.
int chunks = Math.toIntExact( elapsed.dividedBy( chunk ) ); // Returns number of whole times a specified Duration occurs within this Duration.
// Calculate charges.
Integer cost = ( price * chunks );
return cost;
}
Example usage.
final Instant start = Instant.now().minus( Duration.ofMinutes( 21 ) );
final Integer price = 10; // This may come from some other place, such as a look-up in a database.
Integer cost = this.calculateCostForElapsedTimeSoFar( start , price );
System.out.println( "cost: " + cost );
See this code run live at IdeOne.com.
cost: 10
If you want to automatically update the display of the current cost, without the user performing an action such as clicking a button, learn about the Executors framework built into Java. Specifically, see the ScheduledExecutorService. And learn about how to asynchronously updating the widgets within your particular user-interface framework (Vaadin, JavaFX, Swing, etc.). Again, search Stack Overflow for more info, as both of these topics have been covered many times already.
If you are concerned about the clock on your host computer being reset, see an alternative approach by user2023577.

How to convert System.currentMillisSeconds to a TemporalAccessor

I need to convert a standard long System.currentmillis to a temporal accessor and have no clue how to even begin.
Instant is a TemporalAccessor, so you can create an Instant from a number of milliseconds since the epoch:
TemporalAccessor ta = Instant.ofEpochMilli(System.currentTimeMillis());
Note that the docs for System.currentTimeMillis says that the granularity of the value depends on the OS, so it might not be the exact time in milliseconds.
Returns the current time in milliseconds. 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.

System.nanoTime and System.currentTimeMillis()

I am using JDK8 on Windows and JDK8 on Linux
When I run System.nanoTime()/System.currentTimeMillis() on windows, the result is 49,
System.nanoTime(): 74786833960332
System.currentTimeMillis():1507786236263
When run it on Linux, the result is 26236
System.nanoTime(): 39560110918205325
System.currentTimeMillis():1507786262105
I am confused with the result, that the two values are different so much.
Also, I thought that nanoTime is 1,000,000 times milliseconds, so that the two values above both look wrong to me(that is, both of them should be approximately 1000000)
Apples and Oranges
System.nanotime has nothing to do with current date and time-of-day. Its purpose is for calculating elapsed time.
Your math and your comparison to System.currentTimeMillis() makes no sense at all. The two functions are incomparable.
Read the documentation before posting to Stack Overflow.
For date-time handling you should not be using the System class at all. Instead use the industry-leading java.time classes built into Java 8 and later.
If you want current moment in UTC, call Instant.now().
If you want current moment in a time zone, call ZonedDateTime.now.
In Java 9 and later, both classes use a new implementation of Clock to capture the current moment in a resolution up to nanoseconds. But keep in mind that mainstream computers lack a hardware clock with such fine sensitivity. Microseconds is likely the finest resolution you'll see in the real world as of 2017.
According to System.nanotime() docs it is not system time in nanoseconds and it is not related to System.currenTimeMillis. It is platform dependent (this is why the difference) nanoseconds generator and it is used for measuring time elapsed between two invocations.
From the Java System documentation:
[System.nanoTime] Returns the current value of the running Java Virtual Machine's high-resolution time source, in nanoseconds.
This means System.nanoTime() returns the elapsed running time of the JVM in nanos, whereas System.currentTimeMillis() returns the time in milliseconds since midnight, January 1, 1970 UTC.
This results in a non-consistent nanoTime over each run.

Categories

Resources