Forum

> > Trash > [LuaJIT] Fix for os.clock
Forums overviewTrash overviewLog in to reply

English [LuaJIT] Fix for os.clock

2 replies
To the start Previous 1 Next To the start

closed moved [LuaJIT] Fix for os.clock

Starkkz
Moderator Off Offline

Quote
Some of you might not have noticed it yet but the way that os.clock works on Linux is much different than it does on windows even in normal Lua 5.1. It just counts the time that the cpu has been running while it skips the sleep/vsync delay time. This replacement should fix that and it would make it work exactly like in Windows.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
if jit.os == "Linux" or jit.os == "OSX" or jit.os == "BSD" or jit.os == "POSIX" or jit.os == "Other" then
	local ffi = require("ffi")
	ffi.cdef [[
		struct timeval {
			long tv_sec;
			long tv_usec;
		};
		struct timezone {
			int tz_minuteswest;
			int tz_dsttime;
		};
		int gettimeofday(struct timeval *tv, struct timezone *tz);
	]]

	function os.clock()
		local Time = new("struct timeval")
		C.gettimeofday(Time, nil)
		return (Time.tv_sec + Time.tv_usec/1.0e6) - Start
	end

	local StartTimeval = ffi.new("struct timeval"); ffi.C.gettimeofday(StartTimeval, nil)
	local StartTime = StartTimeval.tv_sec + StartTimeval.tv_usec/1.0e6
	setfenv(os.clock, {Start = StartTime, new = ffi.new, C = ffi.C})
end
I was going to upload this code into the File Archive but it was a way too short for that. If you think that it's better if I upload this into the file archive then I'll delete this thread.

Note: Place the code into sys/lua/autorun to get it working.

I placed the thread on this section because Counter-Strike 2D just got LuaJIT, and I intended it for that usage
edited 2×, last 22.06.15 07:16:31 pm

old Re: [LuaJIT] Fix for os.clock

VADemon
User Off Offline

Quote
Can you make a reverse fix for Windows? Thanks.


Just kidding, but you should upload it to the File archive, just in case. IMHO a forum is not a place for useful standalone code snippets
Beware, this behavior (which is different to Windows) might not be limited to Linux. Add the values below as needed.
LuaJIT Docs has written
jit.os
Contains the target OS name: "Windows", "Linux", "OSX", "BSD", "POSIX" or "Other".
To the start Previous 1 Next To the start
Log in to replyTrash overviewForums overview