这个 C# 代码在 Java 中的等价物是什么?
int tick = 0;
tick = Environment.TickCount;
在 Java 中没有让系统正常运行的标准方法。如果你知道你在一个类 Unix 系统上,你可以使用:
Runtime.getRuntime().exec('uptime');
或者您可以读取系统文件:
new Scanner(new FileInputStream("/proc/uptime")).next();
在某些系统上,这也将是 的返回值System.nanoTime()
,但不能保证 的来源System.nanoTime()
(甚至不能保证返回值为正)。
如果您想要这样做的唯一原因是测量经过的时间,您可以使用System.nanoTime()
,或者,如果您想测量经过的挂钟时间(包括在计时时可能进行的任何调整),请使用System.currentTimeMillis()
.
正如@TedHopp 提到的,一种可能性是使用 System.currentTimeMillis()。就我而言,我想要以秒为单位的“滴答计数”,而不是毫秒。这是我目前用于 Java 版本的相应 C# 方法的内容。
// 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);
}