Running time code java

Как замерить время выполнения

Зачастую требуется узнать, сколько времени выполняется тот или иной код. Иногда требуется замерить время выполнения метода или какой-то задачи. В данной статье мы расскажем вам принципы замера времени в Java и покажем лучшие практики для конкретных задач.

Замер времени с помощью currentTimeMills()

Это довольно простой способ измерить время. Метод System.currentTimeMillis() вернёт вам текущее время в миллисекундах. Его потребуется вызвать до выполнения нужной задачи и после, а затем вычислить разницу. В итоге мы узнаем время выполнения в миллисекундах:

long start = System.currentTimeMillis(); // выполнение какой-то логики Thread.sleep(1000); long finish = System.currentTimeMillis(); long elapsed = finish - start; System.out.println("Прошло времени, мс: " + elapsed);

При работе с данным методом следует учитывать его специфику: System.currentTimeMillis() показывает текущее время, основываясь на системных часах и может выдавать некорректный результат.

Замер времени с помощью nanoTime()

Ещё один метод для получения текущего времени это System.nanoTime(). Как следует из названия, этот метод возвращает время с точностью до нансекунд. Также работа этого метода не зависит от системных часов.

Он используется аналогично:

long start = System.nanoTime(); // выполнение какой-то логики Thread.sleep(1000); long finish = System.nanoTime(); long elapsed = finish - start; System.out.println("Прошло времени, нс: " + elapsed);

Для получения значения в миллисекундах результат можно разделить на 1000:

System.out.println("Прошло времени, мс: " + elapsed / 1000000);

Важно: Хотя метод nanoTime() может возвращать время в наносекундах, он не гарантирует, что значения между его вызовами будут обновляться с точностью до наносекунд.

Но всё же это более приемлемый вариант, чем System.currentTimeMillis().

Замер времени с помощью Instant и Duration

В Java 8 добавили новый java.time API. В частности, ля измерения времени подойдут два новых класса – Instant и Duration. Оба эти класса иммутабельны.

Instant обозначает момент времени с начала эпохи Unix (1970-01-01T00:00:00Z). Для создания момента мы используем метод Instant.now(). После того, как мы создали два момент, вычислим разницу в миллисекундах:

Instant start = Instant.now(); // выполнение какой-то логики Thread.sleep(1000); Instant finish = Instant.now(); long elapsed = Duration.between(start, finish).toMillis(); System.out.println("Прошло времени, мс: " + elapsed);

Рекомендуется использовать именно этот подход в Java 8 и выше.

Замер времени выполнения с помощью StopWatch

StopWatch – это класс из библиотеки Apache Commons Lang. Он работает как секундомер. Для его использования сначала требуется подключить библиотеку к проекту:

 org.apache.commons commons-lang3 3.9 

Теперь создадим экземпляр StopWatch. Затем начнём отсчёт с помощью метода start() и окончим отсчёт с помощью метода stop():

public static void stopWatch() throws InterruptedException < StopWatch stopWatch = new StopWatch(); stopWatch.start(); // выполнение какой-то логики Thread.sleep(1000); stopWatch.stop(); System.out.println("Прошло времени, мс: " + stopWatch.getTime()); >

StopWatch удобно использовать тогда, когда в проекте уже подключена данная библиотека.

Исходный код

package ru.javalessons.time; import org.apache.commons.lang3.time.StopWatch; import java.time.Duration; import java.time.Instant; public class MeasureElapsedTime < public static void main(String[] args) throws InterruptedException < currentTimeMillis(); nanoTime(); instant(); stopWatch(); >public static void currentTimeMillis() throws InterruptedException < long start = System.currentTimeMillis(); // выполнение какой-то логики Thread.sleep(1000); long finish = System.currentTimeMillis(); long elapsed = finish - start; System.out.println("Прошло времени, мс: " + elapsed); >public static void nanoTime() throws InterruptedException < long start = System.nanoTime(); // выполнение какой-то логики Thread.sleep(1000); long finish = System.nanoTime(); long elapsed = finish - start; System.out.println("Прошло времени, нс: " + elapsed); >public static void instant() throws InterruptedException < Instant start = Instant.now(); // выполнение какой-то логики Thread.sleep(1000); Instant finish = Instant.now(); long elapsed = Duration.between(start, finish).toMillis(); System.out.println("Прошло времени, мс: " + elapsed); >public static void stopWatch() throws InterruptedException < StopWatch stopWatch = new StopWatch(); stopWatch.start(); // выполнение какой-то логики Thread.sleep(1000); stopWatch.stop(); System.out.println("Прошло времени, мс: " + stopWatch.getTime()); >>

Заключение

В данной статье мы разобрали простые методы замера времени выполнения в Java. Для простых замеров можно использовать все вышеперечисленные методы, кроме currentTimeMillis (из-за того, что он зависит от системных часов).

Читайте также:  Firefox plugins java linux

Источник

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.

Читайте также:  Бинарный поиск python через рекурсию

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:

Источник

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