Kotlin время выполнения метода

Kotlin время выполнения метода

API for representing Duration values and experimental API for measuring time intervals.

Types

AbstractDoubleTimeSource

An abstract class used to implement time sources that return their readings as Double values in the specified unit.

AbstractLongTimeSource

An abstract class used to implement time sources that return their readings as Long values in the specified unit.

ComparableTimeMark

A TimeMark that can be compared for difference with other time marks obtained from the same TimeSource.WithComparableMarks time source.

Duration

Represents the amount of time one instant of time is away from another instant.

DurationUnit

The list of possible time measurement units, in which a duration can be expressed.

TestTimeSource

A time source that has programmatically updatable readings. It is useful as a predictable source of time in tests.

TimedValue

Data class representing a result of executing an action, along with the duration of elapsed time interval.

Читайте также:  Java android webview example

TimeMark

Represents a time point notched on a particular TimeSource. Remains bound to the time source it was taken from and allows querying for the duration of time elapsed from that point (see the function elapsedNow).

TimeSource

A source of time for measuring time intervals.

Annotations

ExperimentalTime

This annotation marks the experimental preview of the standard library API for measuring time and working with durations.

Extensions for External Classes

java.time.Duration

java.util.concurrent.TimeUnit

Properties

days

Returns a Duration equal to this Int number of days.

Returns a Duration equal to this Long number of days.

Returns a Duration equal to this Double number of days.

hours

Returns a Duration equal to this Int number of hours.

Returns a Duration equal to this Long number of hours.

Returns a Duration equal to this Double number of hours.

microseconds

Returns a Duration equal to this Int number of microseconds.

Returns a Duration equal to this Long number of microseconds.

Returns a Duration equal to this Double number of microseconds.

milliseconds

Returns a Duration equal to this Int number of milliseconds.

Returns a Duration equal to this Long number of milliseconds.

Returns a Duration equal to this Double number of milliseconds.

minutes

Returns a Duration equal to this Int number of minutes.

Returns a Duration equal to this Long number of minutes.

Returns a Duration equal to this Double number of minutes.

nanoseconds

Returns a Duration equal to this Int number of nanoseconds.

Returns a Duration equal to this Long number of nanoseconds.

Returns a Duration equal to this Double number of nanoseconds.

seconds

Returns a Duration equal to this Int number of seconds.

Returns a Duration equal to this Long number of seconds.

Returns a Duration equal to this Double number of seconds.

Functions

measureTime

Executes the given function block and returns the duration of elapsed time interval.

measureTimedValue

Executes the given function block and returns an instance of TimedValue class, containing both the result of the function execution and the duration of elapsed time interval.

Executes the given block and returns an instance of TimedValue class, containing both the result of function execution and the duration of elapsed time interval.

Источник

Разное

Исходный код хранится в файлах с расширением .kt (почему не .kot?).

Вычисляем время выполнения кода

В Java есть стандартный способ измерения кода, который мы можем использовать и в Kotlin.

 val startTime = System.currentTimeMillis() // ваш код, который нужно измерить val totalTime = System.currentTimeMillis() - startTime 

Но мы можем использовать другой читаемый код.

 val elapsedTime = measureTimeMillis < // ваш код, который нужно измерить >println("The code took to execute $elapsedTime ms") 

Делаем метод устаревшим (depreCATed)

Наверняка, во время написания кода вы не раз встречали, как студия предупреждает об устаревшей конструкции. Вы можете реализовать такую же возможность и в своём проекте. Особенно это пригодится при создании библиотеки, когда вы не можете просто изменить имя функции, чтобы не сломать обратную совместимость со старыми версиями.

Предположим, у вас была отличная функция feedCat(), в которой выводилось сообщение о необходимости покормить кота. Но в какой-то момент вы поняли, что кормить надо не только котиков, но и другую живность. Нужно сообщить программисту, что в новой версии библиотеки следует использовать новое имя функции — feed(). Вносим изменения в код библиотеки.

 @Deprecated( message = "Используйте функцию feed()", replaceWith = ReplaceWith("feed(name)") ) fun feedCat(name: String) < feed(name) >fun feed(name: String)

Вызываем старую функцию и видим предупреждение. Меняем на новый вариант.

ReplaceWith

По умолчанию уровень устаревшего кода имеет значение DeprecationLevel.WARNING, который мы можем опустить. Также есть уровень ERROR (имя функции будет подчёркнуто красной волнистой чертой) и HIDDEN (имя функции будет выводиться красным цветом).

 @Deprecated( message = "Используйте функцию feed()", level = DeprecationLevel.HIDDEN, replaceWith = ReplaceWith("feed(name)") ) 

Источник

Как использовать встроенные функции Kotlin для измерения времени выполнения кода

Kotlin предоставляет простые способы измерения времени выполнения. Это удобно во многих местах. Вы можете использовать его для сравнения алгоритмов или проверки того, какая часть вашего кода работает медленно.

Давайте сначала рассмотрим классический (в стиле Java) способ измерения времени выполнения. Только тогда мы сможем оценить преимущества Kotlin.

В качестве наглядного примера сравним производительность ArrayList и LinkedList . Мы измеряем время, необходимое для сложения 50 миллионов целых чисел, а затем суммируем их. Проверьте код на GitHub.

Классический способ в стиле Java

Если вы какое-то время работали с Java, то могли видеть что-то подобное (ну, очевидно, это в Java, а не в Kotlin).

Этот подход работает просто отлично, но он имеет недостатки.

Во-первых, мы должны преобразовать результат из наносекунд в секунды. Во-вторых, нам нужно ввести одну или две переменные и длинную строку кода, чтобы получить результат.

Это может привести к путанице, если вам нужно измерить разные части одного и того же метода. Легко случается, что вы вычисляете разницу с неправильными переменными.

Легко видеть, что есть простое решение: извлечение метода измерения времени. Но зачем нам изобретать велосипед?

Kotlin способ измерения времени

мера TimeNanos и мера TimeMillis

Самый простой способ в Kotlin — использовать measureTimeNanos and measureTimeMillis from kotlin.time .

Если вы посмотрите под капот, эти функции делают то же самое, что вы видели выше:

Методы возвращают время выполнения, поэтому нам не нужно их вычислять вручную. Однако нам все еще нужно преобразовать единицу измерения вручную. И есть большая оговорка! Вы не можете получить возвращаемое значение измеряемой функции.

Другой метод, который вы можете использовать, это measureTime. This возвращает Duration object. Duration предлагает вам способы преобразования длительности в нужную вам единицу времени. Однако возвращаемое значение по-прежнему теряется:

Есть, конечно, лучшее решение.

Лучшее из обоих миров: MeasureTimedValue

Пока что я могу получить краткий синтаксис, но не возвращаемое значение или возвращаемое значение и раздутый синтаксис. К счастью, есть способ получить и то, и другое: measureTimedValue .

Вы можете пойти дальше и использовать еще одну классную функцию Kotlin, а именно деструктуризацию:

Это позволяет вам добавлять измерения времени в ваш код. Просто оберните его measureTimedValue и используйте деструктурирование Kotlin, чтобы получить продолжительность и результат кода за один раз.

Если вы посмотрите на код на GitHub, вы, вероятно, заметите аннотацию @OptIn(ExperimentalTime::class) . Нам это нужно, потому что JetBrains пометила более продвинутые методы измерения времени как экспериментальные. В будущем методы могут изменить свое поведение или синтаксис. Вы должны помнить об этом. В любом случае, я бы не рекомендовал использовать эти методы в рабочем коде в долгосрочной перспективе.

Заключение

Измерить время выполнения в Kotlin очень просто. Вы можете просто подключить его по мере необходимости, не загрязняя свою область неоднозначными переменными.

Вот несколько полезных ссылок:

Источник

How To Use Kotlin’s Built-In Functions To Measure Code Execution Time

Investigate performance issues or find out which implementation is best

Kotlin provides straightforward ways to measure execution time. This comes in handy in many places. You can use it to compare algorithms or check which part of your code is slow.

Let us first look at the classic (Java style) way to measure execution time. Only then can we appreciate the benefits of Kotlin.

As an illustrative example, we compare the performance of ArrayList and LinkedList . We measure the time it takes to add 50 million integers and then sum them up. Check out the code on GitHub.

The Classic Java-Style Way

If you have worked with Java for some time, you might have seen something like this (well, obviously, this is in Java, not in Kotlin).

This approach works just fine, but it comes with downsides.

First, we must convert the result from nanoseconds to seconds. Second, we need to introduce either one or two variables and a long line of code to get our result.

This can become messy if you need to measure different parts of the same method. It easily happens that you calculate the differences with the wrong variables.

It is easy to see that there is a simple solution: extracting a method for time measuring. But why should we reinvent the wheel?

The Kotlin Way of Measuring Time

measureTimeNanos and measureTimeMillis

The simplest way in Kotlin is to use measureTimeNanos and measureTimeMillis from kotlin.time .

Источник

Measuring execution times in Kotlin

The Kotlin standard library provides a nice little utility function for measuring the execution time of a block or function.

The function itself is simple, but quite handy, as it prevents the code from getting polluted with calls to System.currentTimeMillis() .

We can call the measureTimeMillis function with any of the following ways:

However, if we pay close attention to the signature of measureTimeMillis we can see that it only accepts functions of type () -> Unit , so we can only use it to measure execution time for functions that return nothing.

So, what if we wanted to measure the running time of a function like the following one?

fun readAndDecodeFile(): File

Let’s see how we can extend measureTimeMillis to achieve our goal with the help of Kotlin’s higher order functions.

The standard measureTimeMillis function returns a Long value which represents the measured execution time. The function that we want to measure also returns a value. So no matter how we wrap our function call inside an overloaded version of measureTimeMillis we will need to find a way to return two values.

One possibility would be to return a Pair . But pairs (and tuples in general) are highly controversial structures in OOP, since they convey no information regarding the semantic relation of the paired values.

Here’s how our extended function would look like, if we were to return a Pair .

No matter what your personal opinion is on this matter, it’s easy to see that it feels wrong pairing the return value of a function with the time it took for the function to run; these two values have very different concerns and storing them together feels unnatural.

We could also argue that the approach above is a bit intrusive at the call site, since it converts

So, what other options do we have? It’s exactly the observation that we made before (that the two values have different concerns), that can help us reach a better solution.

Measuring the execution time of a function is a side-effect of the actual execution of the function, and we should try treating it as such. Normally what we want to do with the result of the measurement is log the result, or record it in an analytics framework.

We can therefore make the measuring function process the execution time internally, without returning it, and only return the actual result of the measured function. Of course this “processing” cannot be predefined, so our measuring function can accept a lambda, that we can use to specify how we want the measurement result to be processed.

The proposed function looks like this:

The usage of this function looks like this:

We can easily appreciate the benefits of this solution. The measurement now is less intrusive: it hasn’t changed the code that much and it can be easily turned off temporarily (by commenting out lines 2 and 4). Higher order functions also help us keep separate the actual logic of the function we are running from the code related to the measurement.

Источник

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