Instantly share code, notes, and snippets.

@alien11689 /loops.groovy Secret
Last active Dec 30, 2018

Embed
What would you like to do?
import java.time.Duration
import java.time.LocalTime
import java.util.stream.LongStream
long n = args.size() > 0 ? args[0] as long : 10
void printAddingTime(String message, long to, Closure<Long> adder) {
LocalTime start = LocalTime.now()
long sum = adder(to)
println("$message: $sum calculated in ${Duration.between(start, LocalTime.now()).toMillis()} ms")
}
printAddingTime('for', n) {
long sum = 0
for (long i = 1; i <= n; ++i) {
for (long j = 1; j <= n; ++j) {
sum += i * j
}
}
sum
}
printAddingTime('while', n) {
long sum = 0
long i = 1
while (i <= n) {
long j = 1
while (j <= n) {
sum += i * j
++j
}
++i
}
sum
}
printAddingTime('LongStream with manual sum', n) {
long sum = 0
LongStream.range(0, n).forEach { i ->
LongStream.range(0, n).forEach { j ->
sum += (i + 1) * (j + 1)
}
}
return sum
}
printAddingTime('LongStream with sum', n) {
LongStream.range(0, n).map { i ->
LongStream.range(0, n).map { j ->
(i + 1) * (j + 1)
}.sum()
}.sum()
}
printAddingTime('times', n) {
long sum = 0
n.times { long i ->
n.times { long j ->
sum += (i + 1) * (j + 1)
}
}
sum
}
printAddingTime('each', n) {
long sum = 0
(1..n).each { i ->
(1..n).each { j ->
sum += i * j
}
}
sum
}
printAddingTime('collect and sum', n) {
(1..n).collect { long i ->
(1..n).collect { long j ->
i * j
}.sum()
}.sum()
}
#!/bin/sh
for x in 10 100 1000 10000 100000; do
echo $x
groovy loops.groovy $x
echo
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment