相当于微时间的Java



我做了一些搜索,但它并没有真正返回任何内容。

但我正在尝试在Java中复制PHP的microtime()函数。我发现了一些像这样的文章,讨论了如何在Javascript中实现它。不过,他们的逻辑是有缺陷的,微时间的毫秒值总是返回0。这就是我目前所拥有的。。。

    long mstime = System.currentTimeMillis();
    long seconds = mstime / 1000;
    double decimal = (mstime - (seconds * 1000)) / 1000;`
    System.out.println(decimal + " " + seconds);

除此之外,由于公式的原因,函数的小数部分(msec等效于php)将始终返回0。我陷入困境,不知所措,需要帮助。

固定代码:

long mstime = System.currentTimeMillis();
long seconds = mstime / 1000;
double decimal = (mstime - (seconds * 1000)) / 1000d;
return decimal + " " + seconds;

(mstime - (seconds * 1000))是一个long,将其除以1000,得到0(长)。

要获得浮点精度,请强制转换为double,或除以double值:

double decimal = (mstime - (seconds * 1000)) / 1000d; // note the d

顺便说一句,如果您需要更高的持续时间精度(时间增量),请使用System.nanoTime()

System.currentTimeMillis()不是那么准确,并且(取决于平台)不会像人们预期的那样以单位增量(1ms)增加。例如,在我的系统(Win7)上,System.currentTimeMillis()的值每15到16毫秒更改一次。

试试这个:

long mstime = System.currentTimeMillis();
float seconds = mstime / 1000;
float decimal = (mstime - (seconds * 1000)) / 1000;
System.out.println(decimal + " " + seconds);

我尝试了一下,并将输出作为:

131.072 1.38548314E9

最新更新