www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 13724] New: std.datetime.timeIt


          Issue ID: 13724
           Summary: std.datetime.timeIt
           Product: D
           Version: D2
          Hardware: x86
                OS: Windows
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: Phobos
          Assignee: nobody puremagic.com
          Reporter: bearophile_hugs eml.cc

I suggest to add to Phobos a very simple function like this timeIt:

import std.stdio, std.datetime, std.typecons;

ulong fibonacci(uint n) {
    if (n == 0 || n == 1)
        return 1;
        return fibonacci(n - 1) + fibonacci(n - 2);

auto timeIt(Callable)(lazy Callable f) {
    StopWatch sw;
    auto result = f();
    return tuple(result, sw.peek.nsecs / 1_000_000_000.0);

void main() {

Output (the second item of the tuple is always in seconds):

Tuple!(ulong, double)(39088169, 2.38505)

The point of this function is to have something very quick and easy to use (so
no configuration arguments, and nothing complex to remember) to time a function
while you write code. For more refined performance testing other things should
be used. This function is useful because it has a minimal cognitive burden and
minimal code to be used.

It's very similar to the Timing function of Mathematica, that is used often:

Nov 12 2014