Task

Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.

Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.

This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.




import std.stdio, std.datetime;
 
int identity(int x) {
    return x;
}
 
int sum(int num) {
    foreach (i; 0 .. 100_000_000)
        num += i;
    return num;
}
 
double timeIt(int function(int) func, int arg) {
    StopWatch sw;
    sw.start();
    func(arg);
    sw.stop();
    return sw.peek().usecs / 1_000_000.0;
}
 
void main() {
    writefln("identity(4) takes %f6 seconds.", timeIt(&identity, 4));
    writefln("sum(4) takes %f seconds.", timeIt(&sum, 4));
}