Java中这个C#代码的等价物是什么?
int tick = 0;
tick = Environment.TickCount;
答案 0 :(得分:2)
没有标准的方法可以在Java中获得系统的正常运行时间。如果你知道你在类Unix系统上,你可以使用:
Runtime.getRuntime().exec('uptime');
或者您可以阅读系统文件:
new Scanner(new FileInputStream("/proc/uptime")).next();
在某些系统上,这也是System.nanoTime()
返回的值,但不保证System.nanoTime()
的来源(或者甚至返回值为正)。
如果你想要这个的唯一原因是测量经过的时间,你可以使用System.nanoTime()
,或者,如果你想测量经过的挂钟时间(包括在做时间时可能做出的任何调整),使用System.currentTimeMillis()
。
答案 1 :(得分:0)
正如@TedHopp所提到的,一种可能性是使用System.currentTimeMillis()。在我的情况下,我希望在几秒钟内“滴答计数”,而不是毫秒。这是我目前正在使用的相应C#方法的Java版本。
// Static field used by the tickCountInSeconds() method
private static long _firstCallTimeSeconds = 0;
...
/**
* Method to get an arbitrary constantly increasing time in seconds, i.e., a time in seconds that
* can be used to compare the relative times of two events, but without having any other meaning.
*
* The .Net version of this method uses the Windows "tick count" facility, but since that doesn't
* exist in Java we fake it by getting the system (Unix-style) time in milliseconds and
* converting it to seconds. But to avoid the "year 2038 problem" (or to avoid criticism for
* creating a year 2038 vulnerability) the time of the first call is saved in a static field and
* subtracted from the returned result.
*/
private synchronized static int tickCountInSeconds() {
long currentTimeSeconds = System.currentTimeMillis() / 1000L;
if (_firstCallTimeSeconds == 0) {
_firstCallTimeSeconds = currentTimeSeconds;
}
return (int)(currentTimeSeconds - _firstCallTimeSeconds);
}