Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Roblox
GitHub Repository: Roblox/luau
Path: blob/master/bench/tests/sieve.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
-- the sieve of of Eratosthenes programmed with coroutines
7
-- typical usage: lua -e N=1000 sieve.lua | column
8
9
-- generate all the numbers from 2 to n
10
function gen (n)
11
return coroutine.wrap(function ()
12
for i=2,n do coroutine.yield(i) end
13
end)
14
end
15
16
-- filter the numbers generated by `g', removing multiples of `p'
17
function filter (p, g)
18
return coroutine.wrap(function ()
19
while 1 do
20
local n = g()
21
if n == nil then return end
22
if n % p ~= 0 then coroutine.yield(n) end
23
end
24
end)
25
end
26
27
local ts0 = os.clock()
28
29
for loops=1,100 do
30
N = 1000
31
x = gen(N) -- generate primes up to N
32
while 1 do
33
local n = x() -- pick a number until done
34
if n == nil then break end
35
-- print(n) -- must be a prime number
36
x = filter(n, x) -- now remove its multiples
37
end
38
end
39
40
local ts1 = os.clock()
41
42
return ts1-ts0
43
end
44
45
bench.runCode(test, "sieve")
46