C++ Coding Exericse – Tiny TimeIt Utility to Time the Applications


Today, I need to measure two command line utilties so I need a ‘timeit’ utility on Windows. You could record the time before and after the command runs and compute the time difference in seconds, but the accuracy in seconds may not be good enough. One easy/better way is to use the Windows API GetTickCount and this should give a fairly good result.

The following C++ source code is compiled into a tiny timeit utility for Win32 platforms (32-bit). Download the single executable Binary (202KB) ad C++ Coding Exericse - Tiny TimeIt Utility to Time the Applications c / c++ tools / utilities here (compiled by Windows GNU C++ Compiler 4.6, RELEASE).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
    https://helloacm.com
*/
#include <iostream>
#include <windows.h>
 
using namespace std;
 
int main(int argc, char** argv) {
    // get tick before running command
    DWORD tick = GetTickCount();
    int rtn = 0;
    if (argc > 1) {
        // run the command sync
        rtn = system(argv[1]);
    }
    // output the difference
    cout << GetTickCount() - tick << endl;
    return rtn;
}
/*
    https://helloacm.com
*/
#include <iostream>
#include <windows.h>

using namespace std;

int main(int argc, char** argv) {
    // get tick before running command
    DWORD tick = GetTickCount();
    int rtn = 0;
    if (argc > 1) {
        // run the command sync
        rtn = system(argv[1]);
    }
    // output the difference
    cout << GetTickCount() - tick << endl;
    return rtn;
}

The system function runs the command (given string parameter) synchronously so the timing difference (between two tick counts) reflect how long the program runs.

Example Usage

The command should be wrapped with double or single quotes:

C:\> timeit "dir /s"
16
C:\> timeit "for /l %f in (1, 1, 1000) do @echo %f > nul"
62

If given with no parameters, timeit should print a single zero. If you don’t need the output, add a redirection >nul to suppress any output.

Github Project: https://github.com/DoctorLai/timeit
–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
373 words
Last Post: How to Read Local Files using HTML5 FileReader?
Next Post: Makefile Tutorial for Beginner - 1

The Permanent URL is: C++ Coding Exericse – Tiny TimeIt Utility to Time the Applications

Leave a Reply