Created
December 29, 2018 07:20
-
-
Save Jura-Z/896e59274aecf06e6f64f3e82bc92f84 to your computer and use it in GitHub Desktop.
Pythagorean Triples, foreach
This file contains 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
import std.stdio; | |
import std.range; | |
import std.typecons; | |
import std.algorithm; | |
import std.concurrency : Generator, yield; | |
import core.time; | |
alias Triple = Tuple!(int, "x", int, "y", int, "z"); | |
void main() | |
{ | |
auto before = MonoTime.currTime; | |
auto gen = new Generator!Triple({ | |
foreach (z; 1..int.max) | |
foreach (x; 1..z+1) | |
foreach (y; x..z+1) | |
if (x*x + y*y == z*z) | |
yield(Triple(x, y, z)); | |
}); | |
foreach (t; gen.take(100)) | |
writefln("%s, %s, %s", t.x, t.y, t.z); | |
auto after = MonoTime.currTime; | |
Duration timeElapsed = after - before; | |
writefln("%s", timeElapsed); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Runtime:
1 ms and 224 μs
Compilation:
~ time dmd foreach.d
dmd foreach.d 0.47s user 0.14s system 99% cpu 0.621 total
~ time dmd foreach.d -O -release -inline -boundscheck=off
dmd foreach.d -O -release -inline -boundscheck=off 1.24s user 0.15s system 99% cpu 1.395 total
MacBook Pro (Retina, 15-inch, Mid 2015), 2,8 GHz Intel Core i7, 16 GB 1600 MHz DDR3