Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Roblox
GitHub Repository: Roblox/luau
Path: blob/master/bench/micro_tests/test_MethodCalls.lua
2725 views
1
local function prequire(name) local success, result = pcall(require, name); return success and result end
2
local bench = script and require(script.Parent.bench_support) or prequire("bench_support") or require("../bench_support")
3
4
function test()
5
6
-- $Id: methcall.lua,v 1.2 2004-06-12 16:19:43 bfulgham Exp $
7
-- http://shootout.alioth.debian.org
8
-- contributed by Roberto Ierusalimschy
9
10
--------------------------------------------------------------
11
-- Toggle class
12
--------------------------------------------------------------
13
14
Toggle = {}
15
16
function Toggle:value ()
17
return self.state
18
end
19
20
function Toggle:activate ()
21
self.state = not self.state
22
return self
23
end
24
25
function Toggle:new (start_state)
26
local o = {state = start_state}
27
self.__index =self
28
setmetatable(o, self)
29
return o
30
end
31
32
33
--------------------------------------------------------------
34
-- NthToggle class
35
--------------------------------------------------------------
36
37
NthToggle = Toggle:new()
38
39
function NthToggle:activate ()
40
self.counter = self.counter + 1
41
if self.counter >= self.count_max then
42
Toggle.activate(self)
43
self.counter = 0
44
end
45
return self
46
end
47
48
function NthToggle:new (start_state, max_counter)
49
local o = Toggle.new(self, start_state)
50
o.count_max = max_counter
51
o.counter = 0
52
return o
53
end
54
55
56
-----------------------------------------------------------
57
-- main
58
-----------------------------------------------------------
59
60
function main ()
61
local start = os.clock()
62
local N = 30000
63
64
local val = 1
65
local toggle = Toggle:new(val)
66
for i=1,N do
67
val = toggle:activate():value()
68
val = toggle:activate():value()
69
val = toggle:activate():value()
70
val = toggle:activate():value()
71
val = toggle:activate():value()
72
val = toggle:activate():value()
73
val = toggle:activate():value()
74
val = toggle:activate():value()
75
val = toggle:activate():value()
76
val = toggle:activate():value()
77
end
78
print(val and "true" or "false")
79
80
val = 1
81
local ntoggle = NthToggle:new(val, 3)
82
for i=1,N do
83
val = ntoggle:activate():value()
84
val = ntoggle:activate():value()
85
val = ntoggle:activate():value()
86
val = ntoggle:activate():value()
87
val = ntoggle:activate():value()
88
val = ntoggle:activate():value()
89
val = ntoggle:activate():value()
90
val = ntoggle:activate():value()
91
val = ntoggle:activate():value()
92
val = ntoggle:activate():value()
93
end
94
print(val and "true" or "false")
95
return os.clock() - start
96
end
97
98
return main()
99
end
100
101
bench.runCode(test, "MethodCalls")
102