Benchmark block

w0rp via Digitalmars-d digitalmars-d at puremagic.com
Mon Mar 30 16:40:17 PDT 2015


On Monday, 30 March 2015 at 23:29:40 UTC, Jonathan wrote:
> I have no idea if this has been discussed yet, but I was 
> thinking it would be neat to have benchmark blocks that only 
> run when specified, like how unittest works.
>
> Code:
>
> benchmarks
> {
>  import std.conv : to;
>  int a;
>  void f() {auto b = to!string(a);}
>  auto r = benchmark!(f)(10_000);
>  auto f0Result = to!Duration(r[0]);
>  writeln(f0Result)
> }
>
> Example:
> rdmd -benchmarks -main myapp.d
>
> Alternatively, the writeln could be replaced with some kind of 
> standard benchmark output utility (similar to the idea of 
> assert when used for unit tests).
>
> Thoughts?

I think this can be implemented via a library solution pretty 
neatly. I was playing with something recently, and I ended up 
writing an RAII benchmark thing.

{
    auto b = Benchmark("name here");

    // Run code here.
}

With the syntax above in mind, you can write a constructor and a 
destructor for Benchmark which start and stop a timer and then 
print the results. I got it working before, and it was kind of 
fun. Another idea is to do this.

@benchmark
void nameHere() {
     // Run code here.
}

Then you can write something or other which finds functions with 
the @benchmark attribute and runs a timer as before, etc.

Why add extra syntax for what you can already do pretty nicely 
with a library?


More information about the Digitalmars-d mailing list