Skip to content

os.clock() returns wall-clock time, not CPU time as Lua specifies #12

Description

@mgrossmann

Split out of #8, which fixed the resolution mismatch but left the underlying semantics
alone.

Problem

Lua specifies os.clock() as "an approximation of the amount in seconds of CPU time used
by the program"
. lua370's os_clock() returns elapsed wall-clock time since the Unix
epoch
instead.

Two consequences:

  • Wrong quantity. The idiomatic benchmark t0 = os.clock() ... os.clock() - t0
    measures elapsed real time, so it counts time the job spent waiting — not CPU consumed.
    Under a loaded system or an I/O-bound script the two diverge arbitrarily.
  • Wrong origin. Portable Lua treats os.clock() as a small number counting from
    program start. Here it is ~1.78e9 and counting from 1970. Differences still work;
    absolute readings do not, and the magnitude can cost float precision in a
    lua_Number.

Root cause

Not a bug in this code. libc370's clock() is a stub:

/* libc370 src/clib/clock.c */
return (clock_t)-1;

os_clock() bypasses it and reads the 64-bit clock directly for exactly that reason — the
comment in src/loslib.c has recorded this since the original port.

Fix

os_clock() already contains the standard Lua implementation, currently behind a disabled
branch:

#else
	lua_pushnumber(L, ((lua_Number)clock())/(lua_Number)CLOCKS_PER_SEC);
#endif

Once libc370 implements clock() for real — reading CPU time from the TCB, e.g. via
TIMEUSEDos_clock() should switch to that branch and drop the __64 arithmetic
entirely. That also retires #11, since CLOCKS_PER_SEC would then correctly
describe the source.

Blocked on libc370

This cannot be done in lua370 alone; it needs clock() implemented first. There is
currently no libc370 issue for that — mvslovers/libc370#49 covered clock64()/time64() and is closed,
and it documented the stub only in passing. Filing one there is the prerequisite for this.

Until then the current behaviour is the best available: a monotonic seconds value with
millisecond resolution, correct for measuring elapsed time, wrong for measuring CPU time.
Worth a note in the docs if any is written before this is resolved.

Ref: #8, mvslovers/libc370#49

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions