Is it correct to measure the speed of code execution in such a way, what are the pros and cons of this approach
long startTime = System.currentTimeMillis(); doSomething(); System.out.println((System.currentTimeMillis() - startTime) + result);
Is it correct to measure the speed of code execution in such a way, what are the pros and cons of this approach
long startTime = System.currentTimeMillis(); doSomething(); System.out.println((System.currentTimeMillis() - startTime) + result);
Here is the code in which there is a warm-up, nanoseconds are used for measurement and not microseconds (more precisely), and the code itself is executed 1000 times, and then the average execution time is found:
public static void main(String[] args) { System.out.println(getTime()); } private static void testMethod() { //Код, время выполнения которого нужно узнать } /** * Метод для измерения времени выполнения метода testMethod * https://stackoverflow.com/a/2404378/7150209 */ private static double getTime() { for (int i = 0; i < 20; i ++) { //прогрев JVM testMethod(); } int count = 1000; //первоначальное кол-во повтора выполнения testMethod while(true) { long begin = System.nanoTime(); for (int i = 0; i < count; i ++) testMethod(); long end = System.nanoTime(); if ((end - begin) < 1000000000) { //Прогон тестов пока суммарное выполнения count раз count *= 100000; //testMethod`a не будет равно несколько секунд continue; } return (double)(end - begin) / count; } }
The test can be performed for a long time. In general, it is recommended to use the JMH library for metering .
Wrong. If the doSomething
method doSomething
well optimized by the JIT compiler, measurements without warming up will not take this into account. If the garbage collector is triggered while doing doSomething
, its running time is doSomething
to the running time of the method. Measuring managed code correctly is a whole art. It is useful to listen to this topic on this topic. And it is better to entrust measurements to a specially developed framework - JMH .
It is impossible to give a definite answer correctly or incorrectly. You can only say how accurate the measurement will be, and this will decide whether it suits you in your situation or not.
Measuring the duration of the operation in this way is possible, but in the general case the results will be very different from reality for a variety of reasons, as you can observe different results in the measurement from measurement to measurement.
However, if the operation is long enough and the results are not very accurate, you can use this method.
For example, in a computer game engine, I use exactly this method of checking some delays.
As @Sergey Gornostaev has already managed to answer for more or less accurate measurements, there are special means and this is an art.
Source: https://ru.stackoverflow.com/questions/947914/
All Articles