example of C types as a substitute for standard Lua types, without using any C function

  • From: razorcam razorcam <luajit@xxxxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Tue, 7 Aug 2012 02:27:26 +0200

Hi I wrote 2 versions of a very simple example of speed optimisation
by using C types as a substitute for standard Lua types, while using
no C function and using only Lua functions.


Obviously, with less boring ffi stuff and without the obligation to
use a table to encapsulate basic C types, like what Cython does well,
it would be better. Mike and the other potential contributors, now you
know what to do ;)

Comments are welcome !


--version with less boring ffi stuff at first, but then a slightly
annoying new() syntax
local ffi=require("ffi")
ffi.cdef[[
typedef struct {int32_t c;} int_c; //you can use any C type, but if
you use int instead of int32_t then the number of bits will be
platform dependent
]]
--end of most of the boring ffi stuff, you can copy/paste it each time
you want to use a C type
local i=ffi.new("int_c",5)  -- the parameter with 5 is optional. why 5
? Because I like the number 5 :), otherwise it seems to default to
zero
print(i.c)
while i.c<999999999 do i.c=i.c+1 end  -- on my Intel Atom, this loop
with C integers is faster than with the only standard number type of
Lua, which is a floating number
print(i.c)


--second version, with more boring ffi stuff at first, but then a
nicer constructor syntax with no need for new()
local ffi=require("ffi")
ffi.cdef[[
typedef struct {int32_t i;} int_c; //you can use any C type, but if
you use int instead of int32_t then the number of bits will be
platform dependent
]]
local mt ={}
local int=ffi.metatype("int_c",mt)
--end of the boring ffi stuff, you can copy/paste it each time you
want to use a C type
local i=int(5)  --why 5 ? Because I like the number 5 :), otherwise it
seems to default to zero
while i.i<999999999 do i.i=i.i+1 end  -- on my Intel Atom, C integers
are faster than the only standard number type of Lua, which is a
floating number
print(i.i)

Other related posts: