Pages

Wednesday, November 16, 2016

This Dprogram shows how you can use the std.datetime module from Phobos, D's standard library, to time the execution of sections of D code. I use the StopWatch class from that module. I print the elapsed time in both milliseconds and in microseconds in this program. (Depending on the functions used from this module and the OS and hardware platform, it may also be possible to measure time to an accuracy of hecto-nanoseconds.

The D documentation for the StopWatch class says:

[ StopWatch measures time as precisely as possible.
This class uses a high-performance counter. On Windows systems, it uses QueryPerformanceCounter, and on Posix systems, it uses clock_gettime if available, and gettimeofday otherwise.
But the precision of StopWatch differs from system to system. It is impossible for it to be the same from system to system since the precision of the system clock varies from system to system, and other system-dependent and situation-dependent stuff (such as the overhead of a context switch between threads) can also affect StopWatch's accuracy. ]

The program for timing D code is below, in the file test_stopwatch.d. It is straightforward, so should be somewhat possible for even people unfamiliar with D to understand. It counts from 1 to 1 billion and measures the time taken for that. Note the use of the more human-readable constant 1_000_000_000, using underscores to separate groups of digits, like Perl can. A nice small D feature. Wish more languages had it.

$ test_stopwatch
Counting from 1 to 1000000000
Time in usecs: 3136388
Time in msecs: 3136
Time in seconds: 3
$ test_stopwatch
Counting from 1 to 1000000000
Time in usecs: 4231483
Time in msecs: 4231
Time in seconds: 4
$ test_stopwatch
Counting from 1 to 1000000000
Time in usecs: 4603806
Time in msecs: 4603
Time in seconds: 4