使用 Java 获得精确到毫秒的经过时间 [英] Getting precise elapsed time using Java to the Millisecond

查看:37
本文介绍了使用 Java 获得精确到毫秒的经过时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找解决我的困境的答案,并找到了一些有用的提示,但没有解决我的具体问题,所以我希望这里有人可以帮助我.

I've been searching for an answer to my dilemma and have found some useful tips but nothing that addresses my specific question, so I was hoping someone here might be able to help me out.

我试图在 Java 中获得精确到毫秒的经过时间.我正在使用 System.nanoTime() 获取当前时间并在以下代码中实现它.请注意,这是我用来测试其精度的代码.

I'm trying to get a precise elapsed time to the millisecond in Java. I'm using System.nanoTime() to get the current time and implementing it in the following code. Mind you, this was code that I used to test it's precision.

long startTime = System.nanoTime()/1000000;
而(真)
{
System.out.println((System.nanoTime()/1000000)-startTime);

long startTime = System.nanoTime()/1000000;
while (true)
{
System.out.println((System.nanoTime()/1000000)-startTime);
}

输出的一部分看起来像这样.

A portion of the output looks like this.

1110
1112
1112
1113
1114
1118
1120

1110
1112
1112
1113
1114
1118
1120

第一位是秒数,第二位是十分之一秒,第三位是百分之几,最后一位是千分之一.你在这里看不到它,但我有百分之一的精度——没有跳过或重复的数字.然而,千分之一远非精确.0 -> 2 -> 2 -> 3 -> 4 -> 8 -> 0.对于我正在做的事情,我需要精确到千分之一,从我读过的所有内容来看,System.nanoTime() 应该是能够提供精确到毫秒.

The first digit is the number of seconds, the second, tenths of a second, the third, hundredths, and then the last is thousandths. You can't see it here, but I have precision to the hundredths place - no skipped or repeated numbers. The thousandths, though, is far from precise. 0 -> 2 -> 2 -> 3 -> 4 -> 8 -> 0. For what I'm doing, I need precision to the thousandths place and from all I have read it seems like System.nanoTime() should be able to provide precision to the millisecond.

我做错了什么还是有其他方法可以精确到毫秒?

Am I doing something wrong or is there another way I can get precision to the millisecond?

推荐答案

这里有两个因素.

首先,即使 System.nanoTime() 也不一定非常精确 - 它只是使用最好的可用时钟(并且不跟随时钟变化,因此它永远不会倒退或向前跳跃).

First, even System.nanoTime() is not necessarily really precise - it just uses the finest clock available (and does not follow clock changes, so it never goes backwards or jumps forward).

其次,您的 Java 程序并不是您计算机上运行的唯一程序 - 因此您的代码(本质上是调用本机 nanoTime 函数和结果的输出)将采取不同的方式每次的时间.例如,一个输出可能需要超过整整毫秒,而另一个只需要一半或更短的时间.

Second, your Java program is not the only program running on your computer - so your code (which essentially is the calling of the native nanoTime function and the output of the result) will take differently much time each time. For example, it may be that one output needs more than a full millisecond while another takes only a half or less.

尝试输出更多的数字(即除以较小的数字),结果将有助于理解.

Try to output some more digits (i.e. divide by a smaller number), the results will be helpful to understand.

这篇关于使用 Java 获得精确到毫秒的经过时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆