java中的Environment.tickcount

问题描述 投票:0回答:3

此 C# 代码在 Java 中的等价物是什么?

int tick = 0;
tick = Environment.TickCount;
java jsp
3个回答
2
投票

Java 中没有让系统正常运行的标准方法。如果您知道自己使用的是类 Unix 系统,则可以使用:

Runtime.getRuntime().exec('uptime');

或者可以读取系统文件:

new Scanner(new FileInputStream("/proc/uptime")).next();

在某些系统上,这也将是

System.nanoTime()
返回的值,但不能保证
System.nanoTime()
的来源(甚至返回值为正)。

如果您想要这样做的唯一原因是测量经过的时间,您可以使用

System.nanoTime()
,或者,如果您想测量经过的挂钟时间(包括在计时时可能进行的任何调整),请使用
System.currentTimeMillis()
.


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);
   }

0
投票
/** A different way to get this information in Tomcat JSP is as such: */
<%@ page import="java.lang.System.*" %>
<body>
<%
long uptime = ((System.nanoTime()) / 1000000);
int days = (int) Math.floor(uptime / 86400000);
int  hours = (int) Math.floor((uptime % 86400000) / 3600000);
int  minutes = (int) Math.floor((uptime % 3600000) / 60000);
int  seconds = (int) Math.floor((uptime % 60000) / 1000);
int  decpart = (int) (uptime % 1);
String struptime = "Days: " + days + ", HMS: " + hours + ":" + minutes + 
":" + seconds;
%>
</body>
/**
The Variable - struptime - can be directly used in a Paragraph, Table or 
the line can be modified to any use.

Andrew Bindner
*/
© www.soinside.com 2019 - 2024. All rights reserved.