Question about Template
simendsjo
simendsjo at gmail.com
Sat Jun 23 08:43:15 PDT 2012
On Sat, 23 Jun 2012 17:30:01 +0200, Michael <pongad at gmail.com> wrote:
> Hello!
> I have a little question about templates. I am trying to write a
> template "timer" that takes a function and times how long the function
> takes to execute. Something like
> auto time = timer!sort(array);
> is equivalent to
> auto start = Clock.currStdTime();
> sort(array);
> auto time = Clock.currStdTime() - time;
>
> except of course that the variable "start" is not created in the former
> case.
>
> The closest I came to the correct template is
> template(alias F) timer {
> auto timer {
> auto start = Clock.currStdTime();
> F();
> return Clock.currStdTime() - time;
> }
> }
>
> The problem with the template is I cannot pass any argument into "F".
> How should I fix this problem?
> Also, I am not entirely sure why I need to write "alias F" instead of
> just "F", any explanation would be appreciated.
>
> Thank you guys,
> Michael
import std.datetime;
import std.traits;
import std.stdio;
struct TimerResult(T) {
TickDuration duration;
T result;
}
auto timer(alias fn, Args...)(Args args) {
auto sw = StopWatch(AutoStart.yes);
auto res = fn(args);
return TimerResult!(typeof(res))(sw.peek, res);
}
T f(T)(T[] arr) {
import core.thread;
Thread.sleep(dur!"seconds"(1));
return arr[0];
}
void main() {
auto res = timer!f([1,2,3,4]);
writeln("first elem: ", res.result);
writeln("time used: ", res.duration.msecs);
}
More information about the Digitalmars-d
mailing list