Skip to content

os.clock in Lua's harness.lua gives surprising results #100

@ltratt

Description

@ltratt

Summary: AWFY Lua is using a surprising time measurement by default, that's probably not what many people want.

In AWFY Lua, harness.lua has this line:

local gettime = ok and socket.gettime or os.clock

CLua doesn't come with socket as standard (it's an external library), so os.clock is normally chosen. Inside CLua that's defined as:

static int os_clock (lua_State *L) {
  lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
  return 1;
}

The man page for clock says:

The clock() function returns an approximation of processor time used by the program.

And, indeed, we've slowly come to realise that the timings we're seeing for AWFY with Lua are "user + sys" time --- which includes whatever random things the process might be doing. For example, if you have multiple threads (say... compilation threads, or other Lua VMs running in a process), the other threads will "corrupt" the timings you're seeing.

There isn't an easy way around this by default AFAICS. CLua doesn't give access to a sensible clock. I'm tentatively using this:

diff --git src/loslib.c src/loslib.c
index ad5a927..5656c4f 100644
--- src/loslib.c
+++ src/loslib.c
@@ -189,6 +189,20 @@ static int os_clock (lua_State *L) {
 }
 
 
+#include <sys/time.h>
+#include "llimits.h"
+static int os_gettime (lua_State *L) {
+  struct timeval tv;
+  if (gettimeofday(&tv, NULL) == 0) {
+    double seconds = tv.tv_sec + tv.tv_usec / 1e6;
+    lua_pushnumber(L, cast_num(seconds));
+    return 1;
+  } else {
+    exit(1);
+  }
+}
+
+
 /*
 ** {======================================================
 ** Time/Date operations
@@ -409,6 +423,7 @@ static const luaL_Reg syslib[] = {
   {"execute",   os_execute},
   {"exit",      os_exit},
   {"getenv",    os_getenv},
+  {"gettime",   os_gettime},
   {"remove",    os_remove},
   {"rename",    os_rename},
   {"setlocale", os_setlocale},

and then the harness.lua line becomes:

local gettime = os.gettime

Perhaps one could force the socket or ffi modules to be installed?

Either way, my guess is that one dosen't want to use os.clock, at least if one expects the resulting numbers to be comparable to other processes / VMs.

[CC @vext01]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions