Посчитать время выполнения программы java

Время выполнения измерения в Java – пример Spring StopWatch

Есть два способа измерить истекшее время выполнения в Java , используя System.currentTimeinMillis () или System.nanoTime (). Эти два метода могут использоваться для измерения прошедшего времени или времени выполнения между двумя вызовами метода или событием в Java. Вычисление истекшего времени – одна из первых вещей, которую Java-программист делает, чтобы узнать, сколько секунд или миллисекунд занимает выполнение метода или сколько времени занимает конкретный блок кода. Большинство программистов на Java знакомы с System.currentTimeInMillis (), которая существует с самого начала, в то время как в Java 1.5 представлена ​​новая версия более точной утилиты измерения времени System.nanoTime, а также несколько новых функций в языке, таких как Generics , типы Enum , auto бокс и переменные аргументы или переменные . Вы можете использовать любой из них для измерения времени выполнения метода в Java. Хотя лучше использовать System.nanoTime () для более точного измерения временных интервалов.

В этом руководстве по Java-программированию мы увидим простую Java-программу для измерения времени выполнения с помощью System.nanoTime () и служебного класса StopWatch фреймворка Spring. Эта статья является продолжением моего поста, посвященного фундаментальным концепциям Java, таким как « Как сравнивать String в Java» , « Как правильно писать метод equals в Java» и « 4 способа зацикливания HashMap в Java» . Если вы еще не прочитали их, вы можете найти их полезными.

Читайте также:  Html css table head

Пример программы Java для измерения времени выполнения в Java

Вот пример кода для измерения прошедшего времени между двумя кодовыми блоками с использованием System.nanoTime, M любых библиотек Java с открытым исходным кодом, таких как Apache commons lang, Google commons и Spring, также предоставляет служебный класс StopWatch, который можно использовать для измерения прошедшего времени в Java . StopWatch улучшает читабельность, сводя к минимуму ошибки вычислений при расчете истекшего времени выполнения, но имейте в виду, что StopWatch не является поточно- ориентированным и не должен использоваться совместно в многопоточной среде, а в его документации четко сказано, что это больше подходит для разработки и тестирования, а не для базовых измерений производительности. выполнение расчета времени в производственной среде.

Источник

Measure Elapsed Time in Java

announcement - icon

As always, the writeup is super practical and based on a simple application that can work with documents with a mix of encrypted and unencrypted fields.

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

Get started with Spring 5 and Spring Boot 2, through the Learn Spring course:

> CHECK OUT THE COURSE

1. Overview

In this article, we’re going to have a look at how to measure elapsed time in Java. While this may sound easy, there’re a few pitfalls that we must be aware of.

We’ll explore standard Java classes and external packages that provide functionality to measure elapsed time.

2. Simple Measurements

2.1. currentTimeMillis()

When we encounter a requirement to measure elapsed time in Java, we may try to do it like:

long start = System.currentTimeMillis(); // . long finish = System.currentTimeMillis(); long timeElapsed = finish - start;

If we look at the code it makes perfect sense. We get a timestamp at the start and we get another timestamp when the code finished. Time elapsed is the difference between these two values.

However, the result may and will be inaccurate as System.currentTimeMillis() measures wall-clock time. Wall-clock time may change for many reasons, e.g. changing the system time can affect the results or a leap second will disrupt the result.

2.2. nanoTime()

Another method in java.lang.System class is nanoTime(). If we look at the Java documentation, we’ll find the following statement:

“This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.”

long start = System.nanoTime(); // . long finish = System.nanoTime(); long timeElapsed = finish - start;

The code is basically the same as before. The only difference is the method used to get timestamps – nanoTime() instead of currentTimeMillis().

Let’s also note that nanoTime(), obviously, returns time in nanoseconds. Therefore, if the elapsed time is measured in a different time unit we must convert it accordingly.

For example, to convert to milliseconds we must divide the result in nanoseconds by 1.000.000.

Another pitfall with nanoTime() is that even though it provides nanosecond precision, it doesn’t guarantee nanosecond resolution (i.e. how often the value is updated).

However, it does guarantee that the resolution will be at least as good as that of currentTimeMillis().

3. Java 8

If we’re using Java 8 – we can try the new java.time.Instant and java.time.Duration classes. Both are immutable, thread-safe and use their own time-scale, the Java Time-Scale, as do all classes within the new java.time API.

3.1. Java Time-Scale

The traditional way of measuring time is to divide a day into 24 hours of 60 minutes of 60 seconds, which gives 86.400 seconds a day. However, solar days are not always equally long.

UTC time-scale actually allows a day to have 86.399 or 86.401 SI seconds. An SI second is a scientific “Standard International second” and is defined by periods of radiation of the cesium 133 atom). This is required to keep the day aligned with the Sun.

The Java Time-Scale divides each calendar day into exactly 86.400 subdivisions, known as seconds. There are no leap seconds.

3.2. Instant Class

The Instant class represents an instant on the timeline. Basically, it is a numeric timestamp since the standard Java epoch of 1970-01-01T00:00:00Z.

In order to get the current timestamp, we can use the Instant.now() static method. This method allows passing in an optional Clock parameter. If omitted, it uses the system clock in the default time zone.

We can store start and finish times in two variables, as in previous examples. Next, we can calculate time elapsed between both instants.

We can additionally use the Duration class and it’s between() method to obtain the duration between two Instant objects. Finally, we need to convert Duration to milliseconds:

Instant start = Instant.now(); // CODE HERE Instant finish = Instant.now(); long timeElapsed = Duration.between(start, finish).toMillis();

4. StopWatch

Moving on to libraries, Apache Commons Lang provides the StopWatch class that can be used to measure elapsed time.

4.1. Maven Dependency

We can get the latest version by updating the pom.xml:

 org.apache.commons commons-lang3 3.12.0 

The latest version of the dependency can be checked here.

4.2. Measuring Elapsed Time With StopWatch

First of all, we need to get an instance of the class and then we can simply measure the elapsed time:

StopWatch watch = new StopWatch(); watch.start();

Once we have a watch running, we can execute the code we want to benchmark and then at the end, we simply call the stop() method. Finally, to get the actual result, we call getTime():

watch.stop(); System.out.println("Time Elapsed: " + watch.getTime()); // Prints: Time Elapsed: 2501

StopWatch has a few additional helper methods that we can use in order to pause or resume our measurement. This may be helpful if we need to make our benchmark more complex.

Finally, let’s note that the class is not thread-safe.

5. Conclusion

There are many ways to measure time in Java. We’ve covered a very “traditional” (and inaccurate) way by using currentTimeMillis(). Additionally, we checked Apache Common’s StopWatch and looked at the new classes available in Java 8.

Overall, for simple and correct measurements of the time elapsed, the nanoTime() method is sufficient. It is also shorter to type than currentTimeMillis().

Let’s note, however, that for proper benchmarking, instead of measuring time manually, we can use a framework like the Java Microbenchmark Harness (JMH). This topic goes beyond the scope of this article but we explored it here.

Finally, as always, the code used during the discussion can be found over on GitHub.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

How To Measure Elapsed Time in Java

Learn to calculate execution time or measure elapsed time of a program or some Java statements using various techniques pre and post Java 8 release.

1. Measuring Elapsed Time since Java 8

If we’re using Java 8 – we can try the new java.time.Instant and java.time.Duration classes. Below Java 8, proceed to the next method down in the article.

To get the elapsed execution time in different time units, use the following method. It measures the duration between two Instants. And Instant represents the time elapsed since the epoch.

long timeElapsed = Duration.between(startInstant, finishInstant).toMillis();
import java.text.ParseException; import java.util.concurrent.TimeUnit; public class Main < public static void main(String[] args) throws ParseException < Instant start = Instant.now(); //Measure execution time for this method methodToTime(); Instant finish = Instant.now(); long timeElapsed = Duration.between(start, finish).toMillis(); //in millis >private static void methodToTime() < try < TimeUnit.SECONDS.sleep(3); >catch (InterruptedException e) < e.printStackTrace(); >> >

This is the most recommended solution to measure elapsed time in Java. It provides nanoseconds level precision of elapsed time between two measurements. It is the most preferred approach to calculate thread execution time in Java.

import java.text.ParseException; import java.util.concurrent.TimeUnit; public class Main < public static void main(String[] args) throws ParseException < long startTime = System.nanoTime(); methodToTime(); //Measure execution time for this method long endTime = System.nanoTime(); long durationInNano = (endTime - startTime); //Total execution time in nano seconds //Same duration in millis long durationInMillis = TimeUnit.NANOSECONDS.toMillis(durationInNano); //Total execution time in nano seconds System.out.println(durationInNano); System.out.println(durationInMillis); >private static void methodToTime() < try < TimeUnit.SECONDS.sleep(3); >catch (InterruptedException e) < e.printStackTrace(); >> >
3000076434 //More precise 3000

If you are not too concerned about nano level precision, or unfortunately still stuck in legacy Java versions – You shall be using System.currentTimeMillis() method.

import java.text.ParseException; import java.util.concurrent.TimeUnit; public class Main < public static void main(String[] args) throws ParseException < long startTime = System.currentTimeMillis(); methodToTime(); //Measure execution time for this method long endTime = System.currentTimeMillis(); long duration = (endTime - startTime); //Total execution time in milli seconds System.out.println(duration); >private static void methodToTime() < try < TimeUnit.SECONDS.sleep(3); >catch (InterruptedException e) < e.printStackTrace(); >> >

We can convert the above time in Millis to other time units such as hours, minutes and seconds to measure execution time in corresponding time units.

Источник

Оцените статью