Skip to content

Instantly share code, notes, and snippets.

@dd86k
Created December 16, 2022 16:32
Show Gist options
  • Save dd86k/4cd9fcb59decdaa6627de57ae505d479 to your computer and use it in GitHub Desktop.
Save dd86k/4cd9fcb59decdaa6627de57ae505d479 to your computer and use it in GitHub Desktop.
Quick benchmark thing for evaluating scoped allocation
import std.stdio;
import std.getopt;
import std.digest.sha : SHA1;
import std.datetime.stopwatch : StopWatch;
import std.range : chunks;
import std.mmfile : MmFile;
import std.file : getSize;
import core.memory : GC;
enum CHUNKSIZE = 4096;
enum TESTLEN = 30_000;
int main(string[] args)
{
bool print;
bool once;
string path;
try
{
GetoptResult res = getopt(args,
config.caseSensitive,
"once", "", &once,
"print", "", &print,
);
if (res.helpWanted)
{
defaultGetoptPrinter("", res.options);
return 0;
}
}
catch (Exception ex)
{
stderr.writeln(ex.msg);
return 1;
}
if (args.length <= 1)
{
stderr.writeln("Missing files");
return 1;
}
foreach (file; args[1..$])
{
path = file;
break;
}
GC.Stats statsA = GC.stats;
StopWatch sw;
sw.start();
if (once)
{
process(path, print);
}
else
{
for (int i; i < TESTLEN; ++i)
{
process(path, print);
}
}
sw.stop();
GC.Stats statsB = GC.stats;
GC.ProfileStats prof = GC.profileStats;
writefln("time=%s", sw.peek() / TESTLEN);
writefln("statsA: heap=%u stack=%u", statsA.usedSize, statsA.allocatedInCurrentThread);
writefln("statsB: heap=%u stack=%u", statsB.usedSize, statsB.allocatedInCurrentThread);
with (prof) {
writefln("gc: num=%u", numCollections);
writefln("gc: Mpause='%s' Mcol='%s'", maxPauseTime, maxCollectionTime);
writefln("gc: Tpause='%s' Tcol='%s'", totalPauseTime, totalCollectionTime);
}
return 0;
}
void printhash(ubyte[] hash)
{
writefln("%(%02x%)", hash);
}
version (MethodA)
void process(string path, bool print)
{
try
{
ulong size = getSize(path);
SHA1 hash;
if (size)
{
MmFile mmfile = new MmFile(path);
foreach (chunk; chunks(cast(ubyte[]) mmfile[], CHUNKSIZE))
{
hash.put(chunk);
}
}
if (print)
printhash(hash.finish());
}
catch (Exception)
{
}
}
version (MethodB)
void process(string path, bool print)
{
import std.typecons : scoped;
try
{
ulong size = getSize(path);
SHA1 hash;
if (size)
{
auto mmfile = scoped!MmFile(path);
foreach (chunk; chunks(cast(ubyte[]) mmfile[], CHUNKSIZE))
{
hash.put(chunk);
}
}
if (print)
printhash(hash.finish());
}
catch (Exception)
{
}
}
version (MethodC)
void process(string path, bool print)
{
try
{
ulong size = getSize(path);
SHA1 hash;
if (size)
{
scope mmfile = new MmFile(path);
foreach (chunk; chunks(cast(ubyte[]) mmfile[], CHUNKSIZE))
{
hash.put(chunk);
}
}
if (print)
printhash(hash.finish());
}
catch (Exception)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment