lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Wed, Jan 25, 2017 at 01:21:36PM +0000, Joseph Manning wrote:
> Dear All,
> 
>    Have you ever wondered how the Lua Team manage to retain their
>    ever-youthful good looks?
> 
>    Do you want to become mega-rich like Biff in Back To The Future II,
>    by placing bets when you already know the outcome?
> 
>    Or would you simply like to run your programs so fast that they
>    actually finish before they've even started?
> 
>    Well, these are all now possible, by using Lua for Time Travel !!!
> 
>    ( ... takes his medication, and a semblance of sanity returns ... )
> 
>    So, I was timing a section of code by wrapping it in calls to
>    'os.clock( )', and under certain conditions, the second such call
>    returned a value that was substantially smaller than the first --
>    in fact, it returned a negative value, which should never happen.

Here's a defect ticket for POSIX discussing the overflow issue.

  http://austingroupbugs.net/view.php?id=686

The issue was brought up with the C committee. (See DR 437 in
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1764.pdf) But they want to
wait and see what solutions the POSIX people suggest. Alas, issue #686
hasn't seen any activity since then.

In C I just explicitly type cast clock_t values (each operand individually)
to unsigned long, and everything just magically works because of modulo
arithmetic. But I'm making assumptions about the platform--that it's two's
complement and that unsigned long is the corresponding unsigned type for
clock_t. I really only use it for debugging and quick benchmarking. But as
mentioned in that ticket there's no [easy] portable way to figure out which
unsigned type to convert to. For Lua you'd probably have to use a function
with conditional logic, just like a portable C solution would likely use.

Usually for this sort of thing it's best to use the system's monotonic
clock--clock_gettime(CLOCK_MONOTONIC) on POSIX systems. On modern Linux
systems the granularity and overhead will be the same as clock().[1]
clock_gettime returns a struct timespec, which is also now the preferred
type for time intervals in the latest C standard, C11.


[1] clock() is implemented as clock_gettime(CLOCK_PROCESS_CPUTIME_ID). And
both CLOCK_PROCESS_CPUTIME_ID and CLOCK_MONOTONIC perform pretty much the
same operations--query the CPU TSC, read some cached values, perform the
arithmetic.