How to get a meaningful result from subtracting 2 nanoTime objects?

扶醉桌前 提交于 2019-12-31 13:17:55

问题


I created a filter that monitors the length of a request.

long start = System.nanoTime();

...

long end = System.nanoTime();

How can I get the number of milliseconds from this now?


回答1:


(end - start) / 1000000

1 microsecond = 1000 nanoseconds

1 millisecond = 1000 microseconds

Note, that the result will be rounded down, but you usually don't get true nanosecond accuracy anyway (accuracy depends on the OS). From the Javadoc on nanoTime():

This method provides nanosecond precision, but not necessarily nanosecond accuracy.




回答2:


Also note that you can use the TimeUnit class to help with conversion. With older versions of Java, the following code might be an example to transform a processing time into some other time format:

long startTime = System.nanoTime();

//Processing in-between.

long endTime = System.nanoTime();
long duration = endTime - startTime;
duration = TimeUnit.SECONDS.convert(duration, TimeUnit.NANOSECONDS);

Note that newer versions of Java have shortcuts in the TimeUnit class.

The above sample will turn nanoseconds long into seconds. Also note that this truncates it so you do lose some precision. Therefore, if you switch to minutes then you will lose the precision of seconds. If you want to get a result of "12 minutes and 32 seconds" then you would have to do further processing with this solution.




回答3:


TimeUnit.NANOSECONDS.toMillis(end - start);

That's all!




回答4:


Just subtract them and divide result by 10^6.

1 nanosecond is 10^-9 seconds and, correspondingly, 10^-6 milliseconds.
http://en.wikipedia.org/wiki/Nano-




回答5:


To get a meaningful result:

void procedure ( ... )
{
     ...
}

double measureProcedure ( double epsilon , ... )
{
    double mean ;
    double stderr = 2 * epsilon ;
    while ( stderr > epsilon )
    {
         long start = System.nanoTime();
         procedure ( ... ) ;
         long end = System.nanoTime();
         // recalculate mean , stderr 
    }
    return ( mean / 1000000 ) ;
}



回答6:


You could just use System.currentTimeMillis().

Caveat:

Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.



来源:https://stackoverflow.com/questions/3654848/how-to-get-a-meaningful-result-from-subtracting-2-nanotime-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!