File: bitbench.lua

package info (click to toggle)
lua-bitop 1.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 200 kB
  • sloc: ansic: 142; makefile: 32
file content (78 lines) | stat: -rw-r--r-- 1,880 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
-- Microbenchmark for bit operations library. Public domain.

local bit = require"bit"

if not bit.rol then -- Replacement function if rotates are missing.
  local bor, shl, shr = bit.bor, bit.lshift, bit.rshift
  function bit.rol(a, b) return bor(shl(a, b), shr(a, 32-b)) end
end

if not bit.bswap then -- Replacement function if bswap is missing.
  local bor, band, shl, shr = bit.bor, bit.band, bit.lshift, bit.rshift
  function bit.bswap(a)
    return bor(shr(a, 24), band(shr(a, 8), 0xff00),
	       shl(band(a, 0xff00), 8), shl(a, 24));
  end
end

local base = 0

local function bench(name, t)
  local n = 2000000
  local s = io.popen("uname -s"):read("*l")
  repeat
    local tm
--  Clock resolution is 10 ms on GNU/Hurd not 1us
    if s == "GNU" then
      tm = 10000*os.clock()
      t(n)
      tm = 10000*os.clock() - tm
    else
      tm = os.clock()
      t(n)
      tm = os.clock() - tm
    end
    if tm > 1 then
      local ns = tm*1000/(n/1000000)
      io.write(string.format("%-15s %6.1f ns\n", name, ns-base))
      return ns
    end
    n = n + n
  until false
end

-- The overhead for the base loop is subtracted from the other measurements.
base = bench("loop baseline", function(n)
  local x = 0; for i=1,n do x = x + i end
end)

bench("tobit", function(n)
  local f = bit.tobit or bit.cast
  local x = 0; for i=1,n do x = x + f(i) end
end)

bench("bnot", function(n)
  local f = bit.bnot
  local x = 0; for i=1,n do x = x + f(i) end
end)

bench("bor/band/bxor", function(n)
  local f = bit.bor
  local x = 0; for i=1,n do x = x + f(i, 1) end
end)

bench("shifts", function(n)
  local f = bit.lshift
  local x = 0; for i=1,n do x = x + f(i, 1) end
end)

bench("rotates", function(n)
  local f = bit.rol
  local x = 0; for i=1,n do x = x + f(i, 1) end
end)

bench("bswap", function(n)
  local f = bit.bswap
  local x = 0; for i=1,n do x = x + f(i) end
end)