7

我有一个简单的 java 程序,我想知道一些操作之间的时间差。对于这个问题,细节并不重要,但让我们看下面的场景。

long beginTime = System.currentTimeMillis();

//Some operations. Let us asssume some database operations etc. which are time consuming.

//

long endTime = System.currentTimeMillis();

long difference = endTime - beginTime;

当代码在机器上运行时,差异会有多可靠?

假设处理器开始执行我的代码中的一些指令,然后将上下文提供给另一个进程,该进程执行一段时间,然后返回执行与该 java 进程相关的指令。

那么,时间差应该取决于我机器的当前状态,即有多少进程正在运行等?那么,在一些操作运行的分析时间里,这种机制不可靠吗?

4

2 回答 2

13

的粒度System.currentTimeMillis()取决于实现和操作系统,通常约为 10 毫秒。

而是使用System.nanoTime()which 返回最精确的可用系统计时器的当前值,以纳秒为单位。请注意,您只能使用它来计算经过的时间,不能将其值用作绝对时间。

例子:

long startTime = System.nanoTime();
// do something you want to measure
long elapsedTimeNs = System.nanoTime() - startTime;
于 2012-10-25T05:57:24.443 回答
2

我认为您的代码会做得很好,因为在几个项目中使用了相同的代码。我认为如果您的代码调用其他数据库进程等,那么它不会对您的时间产生任何影响。在这种情况下它也应该可以正常工作。

前任。

Main Process Started
long beginTime = System.currentTimeMillis();
.
.
.
Called another process (DB or command etc) -> (Another Process start)
                                               .
<Now in this time main process is waiting>     .
                                               .
                                               .
Returned from process                      <- (Another Process end)
.
.
long endTime = System.currentTimeMillis();
long difference = endTime - beginTime;

现在这个差异将是主进程花费的总时间,包括另一个进程花费的时间。这个时间是参考主要过程的机器的,这很好。

于 2012-10-25T06:14:56.257 回答