简体   繁体   English

System.nanotime() 的安全时间来源

[英]Safe time origin for System.nanotime()

I am using a variable time_of_last_call as my origin of time;我使用变量time_of_last_call作为我的时间来源; since nanoTime() might give negative values, I can't use 0 as my origin of time to initialize time_of_last_call .由于nanoTime()可能会给出负值,因此我不能使用 0 作为我的时间原点来初始化time_of_last_call If I initialize time_of_last_call with Long.MIN_VALUE I can have overflow issues.如果我用Long.MIN_VALUE初始化time_of_last_call我可能会Long.MIN_VALUE溢出问题。 Any suggestions?有什么建议?

EDIT: I think I should just initialize it as:编辑:我想我应该将它初始化为:

long time_of_last_call = System.nanoTime()/1000000L;

//long time_of_last_call =Long.MIN_VALUE; //could have overflow issues
//long time_of_last_call =Long.MIN_VALUE/1000000; // could still have overflow issues?

//BEGIN OF CODE WITH A LOOP
// “time_of_last_call” may (or not) be updated: 
if (some_condition) 
    time_of_last_call=System.nanoTime()/1000000L;

if ( ( System.nanoTime()/1000000L - time_of_last_call ) > 10 )
    // do something
//END OF CODE WITH A LOOP

As far as I know, there is no "origin" for nano time.据我所知,纳米时间没有“起源”。 You should only use it to find a difference between two instants in time, in which case the "origin" is irrelevant.您应该只使用它来找到两个瞬间之间的差异,在这种情况下,“原点”是无关紧要的。

In addition, as far as I remember, it's not guaranteed to be consistent over VM restarts.此外,据我所知,不能保证在 VM 重新启动时保持一致。 Therefore, if you persist this value, you can run into some subtle bugs.因此,如果你坚持这个值,你可能会遇到一些微妙的错误。

From the naming of your variables it looks like all you want to do is to track call times.从变量的命名看来,您要做的就是跟踪调用时间。 You most probably don't need the precision and resolution of nano time for this use case, so you'll probably be better off using System.currentTimeMillis() instead.对于此用例,您很可能不需要纳米时间的精度和分辨率,因此最好使用System.currentTimeMillis()代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM