This was written for Windows and may be portable (possibly with minor changes). It had to be C++ to eliminate compile errors.
The table returned by read() is saved as a time reference.
The reference table when passed to elapsed() will return the microSeconds since the reference time. Elapsed time is 32 bits.
// Query Performance Counter Library Module for Lua
// qpc.cpp
#include <windows.h>
#define qpc_cpp
#define LUA_LIB
#include "lua.hpp"
LARGE_INTEGER Frequency;
/*
* get_frequency -
* Returns the frequency of the Performance Counter
*
* Inputs:
* none
* Outputs:
* Frequency
*/
static LARGE_INTEGER get_frequency()
{
LARGE_INTEGER Frequency;
QueryPerformanceFrequency(&Frequency);
return Frequency;
}
/*
* Query_Counter -
* Reads the performance counter returns a table containing low and high 32 bit parts.
*
* Inputs:
* none
* Outputs:
* table of 64 bit count in two 32 bit parts
*
* returns 1.
*/
static int Query_Counter( lua_State *L )
{
LARGE_INTEGER Count;
QueryPerformanceCounter(&Count);
lua_newtable( L );
lua_pushnumber( L, 1 );
lua_pushinteger( L, Count.u.LowPart );
lua_settable( L, -3 );
lua_pushnumber( L, 2 );
lua_pushinteger( L, Count.u.HighPart );
lua_settable( L, -3 );
return 1;
}
static int Elapsed_Time( lua_State *L )
{
#define TABLE 1
LARGE_INTEGER Old_Count;
LARGE_INTEGER uSeconds;
QueryPerformanceCounter(&uSeconds);
luaL_checktype( L, TABLE, LUA_TTABLE );
lua_rawgeti(L, TABLE, 1);
Old_Count.u.LowPart = (luaL_checkint(L, lua_gettop(L)));
lua_pop(L, 1);
lua_rawgeti(L, TABLE, 2);
Old_Count.u.HighPart = (luaL_checkint(L, lua_gettop(L)));
lua_pop(L, 1);
if (uSeconds.QuadPart > Old_Count.QuadPart)
uSeconds.QuadPart -= Old_Count.QuadPart;
else
{
Old_Count.u.LowPart ^= 0xffffffff;
Old_Count.u.HighPart ^= 0xffffffff;
Old_Count.QuadPart += 1;
uSeconds.QuadPart += Old_Count.QuadPart;
}
uSeconds.QuadPart *= 1000000;
uSeconds.QuadPart /= Frequency.QuadPart;
lua_pushinteger(L, uSeconds.u.LowPart);
return 1;
#undef TABLE
}
/*
* qpclib[]
*
* This array provides the relation between the function names and the names used in the Lua script to reference the functions.
*
* The format of this array is defined in the Lua C API.
*
*/
static const luaL_Reg qpc[] = {
{"read", Query_Counter},
{"elapsed", Elapsed_Time},
{NULL, NULL}
};
/*
* luaopen_qpc
*
* This function opens the performance counter library and makes its references known to Lua for scripts.
*
*/
LUALIB_API int luaopen_qpc (lua_State *L) {
luaL_newlib(L, qpc);
Frequency = get_frequency();
return 1;
}
Allan Pfalzgraf
EATON
W126N7250 Flint Drive
Menomonee Falls, WI 53051
tel: 414 449-6872
fax: 414 449-6616
AllanPfalzgraf@eaton.com
www.Eaton.com <http://www.eaton.com/>