Get running time 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() может возвращать время в наносекундах, он не гарантирует, что значения между его вызовами будут обновляться с точностью до наносекунд.

Читайте также:  Php ini on hosted server

Но всё же это более приемлемый вариант, чем 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 (из-за того, что он зависит от системных часов).

Источник

Java Thread: How to Retrieve Its Running Time

One possible solution is to make a call to the operating system, which directs it to pause the thread for a minimum of X milliseconds. However, it cannot be guaranteed that the thread will resume execution precisely after that time, or if the operating system will reschedule it at a later time.

Get running time of a thread java

What is the method to obtain the duration of a thread’s execution in Java, for example, when something() occurs at 00:30 minutes on Thread[n]?

My goal is to create a log file for a software that manages audio files.

Obtain the initial System.nanoTime() and compute the variance at the conclusion. Afterwards, apply TimeUnit to transform it into a more practical measure.

Don’t forget to also examine the MBean called ThreadMXBean as it provides information regarding threads.

In case you prefer not to use nanos, you may opt for the System.currentTimeMillis() function to obtain the current time in milliseconds. Afterwards, you can calculate the elapsed time by subtracting it with the starting time.

Measure execution time for a Java method, A better way would be to run JvisualVM .Just run your method or class and start jvisualVM.Select your java process (if run locally it will list the java process).Go to sampler, monitor CPU, take a snapshot after metod finishes. and you can get time taken by each method in call tree. its buddled in jvm/jdk. – …

Check if the program is idle or running for some time in Java

My goal is to develop a desktop project that features an automatic display of the login screen if the program remains idle for a few minutes. Though I have been advised that http servlet session can accomplish this in web apps, I am unsure of how to implement it in javafx or desktop apps. I would appreciate any guidance or suggestions.

According to the section on Working with Event Filters, there is a possibility of implementing a method such as.

import javafx.application.Application; import javafx.event.EventHandler; import javafx.scene.Scene; import javafx.scene.control.TextField; import javafx.scene.input.KeyEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.StackPane; import javafx.stage.Stage; public class Test extends Application < @Override public void start(Stage primaryStage) < TextField btn = new TextField(); StackPane root = new StackPane(); root.getChildren().add(btn); Scene scene = new Scene(root, 300, 250); scene.addEventFilter(KeyEvent.KEY_PRESSED, new KeyHandler()); scene.addEventFilter(KeyEvent.KEY_RELEASED, new KeyHandler()); scene.addEventFilter(KeyEvent.KEY_TYPED, new KeyHandler()); scene.addEventFilter(MouseEvent.MOUSE_CLICKED, new MouseHandler()); scene.addEventFilter(MouseEvent.MOUSE_ENTERED, new MouseHandler()); scene.addEventFilter(MouseEvent.MOUSE_DRAGGED, new MouseHandler()); scene.addEventFilter(MouseEvent.MOUSE_EXITED, new MouseHandler()); scene.addEventFilter(MouseEvent.MOUSE_MOVED, new MouseHandler()); scene.addEventFilter(MouseEvent.MOUSE_PRESSED, new MouseHandler()); scene.addEventFilter(MouseEvent.MOUSE_RELEASED, new MouseHandler()); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); >protected class KeyHandler implements EventHandler  < @Override public void handle(KeyEvent event) < System.out.println("Key Event"); >> protected class MouseHandler implements EventHandler  < @Override public void handle(MouseEvent event) < System.out.println("Mouse Event"); >> /** * @param args the command line arguments */ public static void main(String[] args) < launch(args); >> 

Essentially, this just furnishes you with details regarding the timing of an occurrence. To implement a «timeout,» you could establish a JavaFX periodic background task.

To avoid the need for constantly stopping and starting the Timeline , my suggestion is to implement a Timeline that runs for a brief duration (around 1-5 seconds). The Timeline would check the duration of the last input and if it surpasses the «time out» period, the login view can be switched to.

To accomplish this, I will utilize Java 8’s recently introduced date/time API. Please refer to the Period and Duration sections for additional information.

PS.

scene.setOnKeyPressed(new KeyHandler()); scene.setOnKeyReleased(new KeyHandler()); scene.setOnKeyTyped(new KeyHandler()); primaryStage.setTitle("Hello World!"); primaryStage.setScene(scene); primaryStage.show(); 

While I haven’t personally tested it, Stage includes both addEventFilter and addEventHandler . These aspects could potentially be utilized to establish the same concept mentioned earlier, but for Stage instead of Scene .

How to time Java program execution speed, You get the current system time, in milliseconds: final long startTime = System.currentTimeMillis (); Then you do what you’re going to do: for (int i = 0; i < length; i++) < // Do something >Then you see how long it took: final long elapsedTimeMillis = System.currentTimeMillis () — startTime; Share.

How long it takes for one second in Java? Measure latency time in Java

My focus is on optimizing the performance through customization and configuration of JVM, OS or kernel. I have no intention to modify the existing code.

I have one second loop (1000 x 1ms)

public static void main(String[] args) throws InterruptedException < long start = System.nanoTime(); for (int i = 0; i < 1000; i++ ) < Thread.sleep(TimeUnit.MILLISECONDS.toMillis(1)); >long duration = System.nanoTime() - start; System.out.println("Loop duration " + duration / TimeUnit.MILLISECONDS.toNanos(1) + " ms."); > 

This loop takes 1055 ms on my Fedora 20 running kernel version 3.12.

The outcome is quite satisfactory, with an average exceeding 1100ms.

Can the speed of this code be enhanced by utilizing customized JVM flags or tweaking the OS configuration?

When you make use of sleep() , you instruct the operating system to pause your thread for a minimum of X milliseconds. However, there is no assurance that the thread will resume execution immediately after the specified time or that the OS will reschedule it later. Additionally, the accuracy and minimum duration of sleep depend largely on the operating system.

In addition, it’s important to consider that your code is likely being interpreted (JAva compiles) rather than executed as native code ( hotspots ). This is where the name Hotspot JIT originates, as it frequently executes the compiled code. For a server VM, this occurs after 10,000 executions of a specific code. However, in your case, it only happens after 1,000 executions.

Please take note that your code is not just waiting for one second, it includes executing for loop, initializing variables to keep track of it and iterating. Additionally, it’s important to comprehend the other processes taking place within your system.

The scheduler in your operating system decides which running program (or process) can have access to the CPU at a given time. If your program goes to sleep (meaning it doesn’t do anything for a specified period of time), the scheduler will often replace it with another program that is also running. When your program is switched back in is unpredictable. Therefore, even if your program is switched back in close to the one-second mark (which is likely), it is unlikely to be exactly at one second. Improving the code will not address the underlying issue, which is the desire for an exactly one-second loop.

It is important to note that the scheduler can switch out a program anytime, even if it does not intend to go to sleep. The role of the scheduler is to determine which processes have access to system resources at a given time. Therefore, time-profiling in a half-implemented manner is not very effective. For better results, IDE profiler should be used as it measures wall time and other factors.

Perhaps you should consider exploring http://en.wikipedia.org/wiki/Real_time_Java for ensuring low-latency guarantees. This requires both a JVM and an OS optimized for this purpose.

One of the reasons for the delay of 55 ms could be attributed to the kernel system tick time, which varies depending on the type of system (200 tps for desktops, 100 for servers, and 1000 for RT systems). These delays may seem insignificant individually but accumulate over time. Furthermore, the sleep function call will inevitably incur some system overhead, which cannot be reduced independently.

How to measure execution time for a Java method?, The now () method of the Instant class returns the current time and the Duration.between () methods returns the difference between the given two time values to get the elapsed time retrieve the time values before and after the execution of the desired method and retrieve the duration using the …

Источник

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.

Источник

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