How can I set the program time in seconds? - java

I want to give the program time in java. How can I get the time in seconds?
This is my program:
public static void main(String[] args) {
long start = System.nanoTime();
System.out.print(start);
}
For example when i run the program show 7955739220574 nano time. that mean's 7955 second.
Is this time is really for this program!!!!!?
Thank you.

Please note that System.nanoTime() returns the time in nanoseconds which passed since an arbitrary point in time, not necessarily the beginning of your program. System.currentTimeMillis() will give you the absolute time in milliseconds since the Unix epoch (Jan 1, 1970).
If you want to measure the duration of something you can do:
long startTime = System.nanoTime();
// ... the code being measured ...
long estimatedTime = System.nanoTime() - startTime;
... as showed in the docs i linked. If you want it in seconds you should divide estimatedTime it by 1 billion.

You could use TimeUnit:
TimeUnit.SECONDS.convert(time, TimeUnit.NANOSECONDS);

Divide the result you get in nanoseconds by 1 000 000 000.

1 nanosecond is 10^-9 * 1 seconds.
so to get seconds using nano seconds, you need to divide the value of Start by 10^-9

Related

Fastest way to get nanos unix epoch time in Java

I currently do this to successfully get the current epoch time in nanos:
Instant inst = Instant.now();
long time = inst.getEpochSecond();
time *= 1000000000l;
time += inst.getNano();
However, it's a bit too slow for my use case, taking around 1us each call after the JVM has warmed up.
Is there a faster way to do it?
I'm happy with a solution that gives me the microseconds since epoch, as long as it's faster than the above.
What may work is to run:
long n1 = System.nanoTime();
long m = System.currentTimeMillis();
long n2 = System.nanoTime();
a number of times until the difference between n1 and n2 is less than the resolution you want (it's about 400 ns on my PC after a couple of iterations).
You can then use the difference between n1 (or n2 or an average of the 2...) and m * 1e6 as an offset that you need to add to System.nanoTime() to get the current epoch nanos.
Disclaimer:
System.nanoTime doc explicitly states that the resolution is at least that of System.currentTimeMillis(), which may be > 1 ms. So no guarantee that you will get microsecond resolution.
Corollary: this probably doesn't work in all environments (you may never get n2-n1 small enough - or it may be 0 just because the resolution of your system is too low).
System.nanoTime() may be out of sync over long periods - so this is a trade off between precision and performance.
You also need to account for possible arithmetic overflow.
See also: Current time in microseconds in java

System.nanoTime / System.currentTimeMillis = 107 (should this be 1e6 ?)

According to java.lang.System API
currentTimeMillis() Returns the current time in milliseconds
nanoTime() Returns the current value of the running Java Virtual
Machine's high resolution time source, in nanoseconds.
Strictly speaking a nanosecond is 1e-9 and millisecond is 1e-3. Therefore, a duration in nanosecs must be a multiple of 1e6 of the same duration in millisecs. This is not the case in practice, what is the reason?
scala> System.nanoTime / System.currentTimeMillis
res0: Long = 107
System.nanoTime() has an arbitrary start point; it's not unix epoch. From the Javadoc:
The value returned represents nanoseconds since some fixed but arbitrary origin time
So what you're actually calculating there is:
(unknownOffset + offsetFromEpochInNanos) / offsetFromEpochInMillis
which will almost certainly not be 1e6, unless unknownOffset happens to be arbitrarily zero.
If you can remove the effect of the unknown offset by subtracting the two times, you can see that the ratio is around 1e6:
long nanoStart = System.nanoTime();
long milliStart = System.currentTimeMillis();
Thread.sleep(2000);
long nanoEnd = System.nanoTime();
long milliEnd = System.currentTimeMillis();;
long nanoDelta = nanoEnd - nanoStart;
long milliDelta = milliEnd - milliStart;
System.out.println((double) nanoDelta / milliDelta);
Output (running 5 times):
1000058.3725
1000045.4705
999549.1579210395
1000046.101
1000038.1045
Ideone demo
So, pretty close to 1e6.
Note that it might not be this, because System.currentTimeMillis() doesn't progress smoothly, owing to corrections for clock skew. However, these should be infrequent, so most of the time when you run this code, you'll see roughly 1e6.

System.currentTimeMillis() only updating every 128 seconds?

I have a loop in which I am checking seconds elapsed by doing t-(long)(System.currentTimeMillis()/1000.0f) where t is set to t=(long)(System.currentTimeMillis()/1000.0f) right before the loop. I find that (long)(System.currentTimeMillis()/1000.0f) is equal to t for the first 128 seconds. It then updates after another 128 seconds. I am doing this on a background thread. What am I doing wrong?
System.currentTimeMillis() is a sufficiently large value that float cannot represent all integers around that range.
The fix is to simply use integer division by 1000.
You can use this to convert milis to second
long timeMillis = System.currentTimeMillis();
long timeSeconds = TimeUnit.MILLISECONDS.toSeconds(timeMillis);

java.sql.Timestamp way of storing NanoSeconds

java.sql.Timestamp constructor go like this:
public Timestamp(long time) {
super((time/1000)*1000);
nanos = (int)((time%1000) * 1000000);
if (nanos < 0) {
nanos = 1000000000 + nanos;
super.setTime(((time/1000)-1)*1000);
}
}
It basically accepts time in millisecond and then extracts the last 3 digits and makes it nanos. So for a millisecond value of 1304135631 421, I'm getting Timestamp.getnanos() as
421000000. This is plain calculation (adding 6 zeroes at the end)... does not seems to be optimum.
A better way could have been Timestamp constructor that accepts time in nanoseconds and then calculates the nanosecond value out of that.
If you run the below program, you'll see the difference between actual nanoseconds and the one returned by Timestamp way of calculating nanosecods.
long a = System.currentTimeMillis();
for(;;){
long b = System.currentTimeMillis();
Timestamp tm = new Timestamp(System.currentTimeMillis());
System.out.println(tm.getTime());
System.out.println(tm.getNanos());
System.out.println("This is actual nanos" + System.nanoTime()%1000000000);
System.out.println("--------------------------");
if(b-a >= 1)
break;
}
So all the discussion about Timestamp that says it stores time up to nanoseconds , does not seems to be so correct.. Isn't?
The time in millis does not represent the time in nanos. More precise it simply can't be. You're supposed to use Timestamp#setNanos() to set the real nanos.
long timeInMillis = System.currentTimeMillis();
long timeInNanos = System.nanoTime();
Timestamp timestamp = new Timestamp(timeInMillis);
timestamp.setNanos((int) (timeInNanos % 1000000000));
// ...
Since the introduction of java.time.*, there is a new factory method in java.sql.Timestamp: Timestamp.from(Instant.now()) will do the job (with nanoseconds precision). There is also Timestamp.toInstant() to convert it the other way around.
Although it's an old post, I would like to add that the docs of Timestamp does state that it "holds fractional seconds by allowing the specification of
fractional seconds to a precision of nanaoseconds". The confusing part is "hold". This seems confusing at first but if understood correctly, it actually does not state that it holds nanaoseconds
value.It says it "holds" fractional value and allows it to be a "precision" of nanoseconds. Precision should be understood in terms of representation
of total number of digits. So it essentially means that the part is actually fractional (still milliseconds) but is multiplied by 1000000 to represent it as nanoseconds.
The accepted answer (by ever helpful BaluC) sums it up nicely.
I like OpenJPA's implementation of TimestampHelper. It use static initializers to keep track of elapsed nanoseconds between calls to make a timestamp.

Java System.nanoTime() huge difference in elapsed time

I'm in and android widget and checking elapsed time between two calls of System.nanoTime() and the number is huge. How do you measure elapsed time with this? it should be a fraaction of a second and instead its much more. Thanks
The System.nanoTime() returns a time value whose granularity is a nanosecond; i.e. 10-9 seconds, as described in the javadoc. The difference between two calls to System.nanoTime() that are a substantial fraction of a second apart is bound to be a large number.
If you want a time measure with a larger granularity, consider System.currentTimeMillis() ... or just divide the nanosecond values by an appropriate power of 10 to suit your application.
Note that on the Android platform there are 3 distinct system clocks that support different "measures" of time; see SystemClock. If you are programming explicitly for the Android platform, you should read the javadoc and decide which measure is most appropriate to what you are doing.
For your information, "nano-" is one of the standard prefixes defines by the International System of Units (SI) - see http://physics.nist.gov/cuu/Units/prefixes.html.
If you really think that "they" got it wrong and that "nano-" is too small, you could always write a letter to the NIST. I'm sure someone would appreciate it ... :-)
One seconds contains 1,000,000,000 nanoseconds, so as long as your number is in that range, it's reasonable.
If you want it in fractional form, just take your value / 10^9 where value is your difference in nanoTime()s.
long nanoSeconds = 500000000;
float seconds = nanoSeconds / 1000000000;
Log.i("NanoTime", nanoSeconds + " ns is the same as " + seconds + " seconds");
Your output would be:
07-27 11:35:47.196: INFO/NanoTime(14237): 500000000 ns is the same as 0.5 seconds

Categories

Resources