
ru.tinkoff.plugins.buildmetrics.utils.IntervalUtils.kt Maven / Gradle / Ivy
package ru.tinkoff.plugins.buildmetrics.utils
import java.util.LinkedList
fun Iterable>.mergeIntervals(): Iterable> {
val intervals = this.sortedBy { it.first }
val merged = LinkedList>()
for (interval in intervals) {
if (merged.isEmpty() || merged.last().second < interval.first) {
merged.add(interval)
} else {
val mergedInterval = merged.last.run { copy(second = maxOf(second, interval.second)) }
merged.apply {
removeLast()
addLast(mergedInterval)
}
}
}
return merged
}
/**
* The sum of the difference between the start and end values of overlapping intervals.
*
* Example:
* ```kotlin
* println(mutableListOf(0L to 3L).wallClockTime())
* // output 3
* println(mutableListOf(0L to 3L, 0L to 5L).wallClockTime())
* // output 5
* println(mutableListOf(0L to 5L, 10L to 15L).wallClockTime())
* // output 10
* println(mutableListOf(0L to 5L, 10L to 15L, 3L to 11L).wallClockTime())
* // output 15
* ```
* @return the sum of the difference between the start and end values of overlapping intervals.
*/
fun Iterable>.wallClockTime(): Long = mergeIntervals().serialTime()
/**
* The sum of the difference between the start and end values of intervals.
*
* Example:
* ```kotlin
* println(mutableListOf(0L to 3L).serialTime())
* // output 3
* println(mutableListOf(0L to 3L, 0L to 5L).serialTime())
* // output 8
* println(mutableListOf(0L to 5L, 10L to 15L).serialTime())
* // output 10
* println(mutableListOf(0L to 5L, 10L to 15L, 3L to 11L).serialTime())
* // output 18
* ```
* @return the sum of the difference between the start and end values of overlapping intervals.
*/
fun Iterable>.serialTime(): Long = sumOf { interval -> interval.second - interval.first}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy