1-- Microbenchmark for bit operations library. Public domain. 2 3local bit = require"bit" 4 5if not bit.rol then -- Replacement function if rotates are missing. 6 local bor, shl, shr = bit.bor, bit.lshift, bit.rshift 7 function bit.rol(a, b) return bor(shl(a, b), shr(a, 32-b)) end 8end 9 10if not bit.bswap then -- Replacement function if bswap is missing. 11 local bor, band, shl, shr = bit.bor, bit.band, bit.lshift, bit.rshift 12 function bit.bswap(a) 13 return bor(shr(a, 24), band(shr(a, 8), 0xff00), 14 shl(band(a, 0xff00), 8), shl(a, 24)); 15 end 16end 17 18local base = 0 19 20local function bench(name, t) 21 local n = 2000000 22 repeat 23 local tm = os.clock() 24 t(n) 25 tm = os.clock() - tm 26 if tm > 1 then 27 local ns = tm*1000/(n/1000000) 28 io.write(string.format("%-15s %6.1f ns\n", name, ns-base)) 29 return ns 30 end 31 n = n + n 32 until false 33end 34 35-- The overhead for the base loop is subtracted from the other measurements. 36base = bench("loop baseline", function(n) 37 local x = 0; for i=1,n do x = x + i end 38end) 39 40bench("tobit", function(n) 41 local f = bit.tobit or bit.cast 42 local x = 0; for i=1,n do x = x + f(i) end 43end) 44 45bench("bnot", function(n) 46 local f = bit.bnot 47 local x = 0; for i=1,n do x = x + f(i) end 48end) 49 50bench("bor/band/bxor", function(n) 51 local f = bit.bor 52 local x = 0; for i=1,n do x = x + f(i, 1) end 53end) 54 55bench("shifts", function(n) 56 local f = bit.lshift 57 local x = 0; for i=1,n do x = x + f(i, 1) end 58end) 59 60bench("rotates", function(n) 61 local f = bit.rol 62 local x = 0; for i=1,n do x = x + f(i, 1) end 63end) 64 65bench("bswap", function(n) 66 local f = bit.bswap 67 local x = 0; for i=1,n do x = x + f(i) end 68end) 69 70