I wrote a module to ease time measurement in my projects.
Does anyone know how to get elapsed milli- or nanoseconds under linux? Want to make it portable :)



module time;

version(Windows)
        import std.c.windows.windows;


long frequency;                 /// frequency of the high performance counter
long startTime;                 /// current measurement start time
long curTime;                   /// current measurement end time
const bool hpcAvailable;/// high performance counter supported?

/**
 * initialize the high performance counter
 */
static this()
{
        version(Win32)
        {
                QueryPerformanceFrequency (&frequency);
                hpcAvailable = false;
                if (frequency)
                {
                        hpcAvailable = true; // high performance counter not 
supported
                        pragma(msg, "high performance counter available");
                }
        }
}

/**
 * start measurement
 */
void start()
{
        version(Windows)
        {
                if (hpcAvailable)
                        QueryPerformanceCounter(&startTime);
                else
                {
                        version(Win32)
                                startTime = GetTickCount();
                        version(Win64)
                                startTime = GetTickCount64();
                }
        }
}

/**
 * get elapsed milliseconds
 */
double msecs()
{
        version(Windows)
        {
                if (hpcAvailable)
                {
                        QueryPerformanceCounter(&curTime);
                        return ((curTime-startTime) * 1000) / cast(double) 
frequency;
                }
                else
                {
                        version(Win32)
                                curTime = GetTickCount();
                        version(Win64)
                                curTime = GetTickCount64();
                        return (curTime-startTime);
                }
        }
}

/**
 * get elapsed nanoseconds
 */
double nsecs()
{
        version(Windows)
        {
                if (hpcAvailable)
                {
                        QueryPerformanceCounter(&curTime);
                        return ((curTime-startTime) * 1000000) / cast(double) 
frequency;
                }
                else
                {
                        version(Win32)
                                curTime = GetTickCount();
                        version(Win64)
                                curTime = GetTickCount64();
                        return (curTime-startTime) * 1000;
                }
        }
}

Reply via email to