time measurement under linux?

Trass3r mrmocool at gmx.de
Mon Jan 19 07:18:01 PST 2009


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;
		}
	}
}


More information about the Digitalmars-d-learn mailing list