Last active
January 1, 2016 22:29
-
-
Save dmahapatro/8210462 to your computer and use it in GitHub Desktop.
Performance hit using groovy-stream.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Project Euler # 10 | |
//http://projecteuler.net/problem=10 | |
@Grab(group='org.gperfutils', module='gbench', version='0.4.2-groovy-2.1') | |
@Grab( 'com.bloidonia:groovy-stream:0.6.2' ) | |
import groovy.stream.Stream | |
import groovyx.gbench.Benchmark | |
def usingStream(){ | |
def isPrime = {n-> | |
for (int i=2;i<n;i++) { | |
if (n%i==0) return false | |
} | |
true | |
} | |
Stream s = Stream.from 2..200000 filter {isPrime(it)} | |
println s.collect().sum() | |
} | |
def isPrime(num, primes) { | |
primes.find { it <= Math.sqrt(num) && it != 1 && it != num && num % it == 0 } == null | |
} | |
def oldAddPrimes(){ | |
def primes = [] | |
def min = 2 | |
def max = 200000 | |
(min..max).findAll { it % 2 == 1 || it == 2 }.each { i -> | |
if (isPrime(i, primes)) | |
{ | |
primes.add(i); | |
} | |
} | |
println primes.sum() //1709600813 | |
} | |
def addAllPrimes(){ | |
def primes = 0 | |
def min = 2 | |
def max = 200000 | |
(min..max).each { x -> | |
if ((2..Math.sqrt(x)).every{x % it != 0}) { | |
primes += x | |
} | |
} | |
println primes //1709600811 | |
} | |
def r = benchmark{ | |
'Stream'{usingStream()} | |
'oldAdd'{oldAddPrimes()} | |
'newAdd'{addAllPrimes()} | |
} | |
r.prettyPrint() | |
//Output | |
Environment | |
=========== | |
* Groovy: 2.2.1 | |
* JVM: Java HotSpot(TM) 64-Bit Server VM (23.1-b03, Oracle Corporation) | |
* JRE: 1.7.0_05 | |
* Total Memory: 105.5625 MB | |
* Maximum Memory: 113.8125 MB | |
* OS: Windows 7 (6.1, amd64) | |
Options | |
======= | |
* Warm Up: Auto (- 60 sec) | |
* CPU Time Measurement: On | |
1709600813 | |
1709600813 | |
1709600813 | |
user system cpu real | |
Stream 106735856049 46821120 106782677169 109959313815 | |
oldAdd 18111696454 15614468 18127310922 18704594910 | |
newAdd 9562843119 13489 9562856608 9601082963 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment