[Issue 4124] toString() for BitArray and more
d-bugmail at puremagic.com
d-bugmail at puremagic.com
Thu Oct 13 11:22:59 PDT 2011
http://d.puremagic.com/issues/show_bug.cgi?id=4124
--- Comment #1 from bearophile_hugs at eml.cc 2011-10-13 11:22:06 PDT ---
Maybe the usefulness of isSet(), set(), and reset() methods is visible with two
benchmarks. They implement the same algorithm (a simple sieve), the first uses
a BitArray, and the second a manually implemented bit array. On my 32 bit
system the second program is about two times faster than the first one.
import std.stdio, std.algorithm, std.range, std.math, std.bitmanip,
std.datetime;
uint[] primes(uint n) {
if (n < 2) return [];
BitArray F;
F.length = n + 1;
F[0] = true;
F[1] = true;
foreach (i; 2 .. cast(uint)sqrt(n))
if (!F[i])
for (uint j = i * i; j <= n; j += i)
F[j] = true;
return array(filter!((i){ return !F[i]; })(iota(n+1)));
}
void main() {
StopWatch sw;
sw.start();
primes(30_000_000);
sw.stop();
writeln(sw.peek().msecs / 1000.0);
}
import std.stdio, std.algorithm, std.range, std.math, std.datetime;
size_t[] primes(in size_t n) {
enum size_t bpc = size_t.sizeof * 8;
auto F = new size_t[n / bpc + 1];
F[] = size_t.max;
bool isSet(in size_t i) nothrow {
immutable size_t offset = i / bpc;
immutable size_t mask = 1 << (i % bpc);
return (F[offset] & mask) != 0;
}
void clear(in size_t i) nothrow {
immutable size_t offset = i / bpc;
immutable size_t mask = 1 << (i % bpc);
if ((F[offset] & mask) != 0)
F[offset] = F[offset] ^ mask;
}
clear(0);
clear(1);
foreach (i; 2 .. cast(size_t)sqrt(n))
if (isSet(i))
for (uint j = i * i; j <= n; j += i)
clear(j);
return array(filter!isSet(iota(n + 1)));
}
void main() {
StopWatch sw;
sw.start();
size_t n = primes(30_000_000).length;
sw.stop();
writeln(sw.peek().msecs / 1000.0);
writeln("n primes: ", n);
}
--
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
More information about the Digitalmars-d-bugs
mailing list