1+ -- The Computer Language Benchmarks Game
2+ -- https://salsa.debian.org/benchmarksgame-team/benchmarksgame/
3+ -- contributed by Mike Pall
4+ -- modified by Sebastian Engel to be parallel, derived from mandelbrot-lua-6
5+
6+ -- called with the following arguments on the command line;
7+ -- 1: Initial depth of the tree
8+ -- 2: number of children to spawn (defaults to 6, which works well on 4-way)
9+ -- If this is a child, then there will be additional parameters;
10+ -- 3: current tree depth
11+ -- 4: chunk start
12+ -- 5: chunk end
13+
14+
15+ local N = tonumber (arg and arg [1 ]) or 0
16+ local children = tonumber (arg and arg [2 ]) or 4
17+ local cdepth = tonumber (arg and arg [3 ])
18+ local chunkstart = tonumber (arg and arg [4 ])
19+ local chunkend = tonumber (arg and arg [5 ])
20+
21+ local write = io.write
22+
23+ local function BottomUpTree (depth )
24+ if depth > 0 then
25+ depth = depth - 1
26+ local left , right = BottomUpTree (depth ), BottomUpTree (depth )
27+ return { left , right }
28+ else
29+ return { }
30+ end
31+ end
32+
33+ local function ItemCheck (tree )
34+ if tree [1 ] then
35+ return 1 + ItemCheck (tree [1 ]) + ItemCheck (tree [2 ])
36+ else
37+ return 1
38+ end
39+ end
40+
41+ if not chunkstart then
42+ -- we are the parent process.
43+ -- emit the header, and then spawn children
44+
45+ local mindepth = 4
46+ local maxdepth = mindepth + 2
47+ if maxdepth < N then maxdepth = N end
48+
49+ do
50+ local stretchdepth = maxdepth + 1
51+ local stretchtree = BottomUpTree (stretchdepth )
52+ write (string.format (" stretch tree of depth %d\t check: %d\n " ,
53+ stretchdepth , ItemCheck (stretchtree )))
54+ end
55+
56+ local longlivedtree = BottomUpTree (maxdepth )
57+
58+ for depth = mindepth ,maxdepth ,2 do
59+ local iterations = 2 ^ (maxdepth - depth + mindepth )
60+ local check = 0
61+
62+ local workunit = math.floor (iterations / children )
63+ local handles = { }
64+
65+ for i = 1 ,children do
66+ local cs , ce
67+
68+ if i == 1 then
69+ cs = 1
70+ ce = workunit
71+ elseif i == children then
72+ cs = (workunit * (i - 1 )) + 1
73+ ce = iterations
74+ else
75+ cs = (workunit * (i - 1 )) + 1
76+ ce = cs + workunit - 1
77+ end
78+
79+ handles [i + 1 ] = io.popen ((" %s %s %d %d %d %d %d" ):format (
80+ arg [- 1 ], arg [0 ], N , children , depth , cs , ce ))
81+ end
82+
83+ -- collect answers, and emit
84+ for i = 1 , children do
85+ check = check + (handles [i + 1 ]:read " *a" )
86+ end
87+
88+ write (string.format (" %d\t trees of depth %d\t check: %d\n " ,
89+ iterations , depth , check ))
90+ end
91+
92+ write (string.format (" long lived tree of depth %d\t check: %d\n " ,
93+ maxdepth , ItemCheck (longlivedtree )))
94+
95+ else
96+ -- we are a child process.
97+ -- do the work allocated to us.
98+ local partialcheck = 0
99+
100+ for i = chunkstart ,chunkend do
101+ partialcheck = partialcheck + ItemCheck (BottomUpTree (cdepth ))
102+ end
103+
104+ write (partialcheck )
105+ end
0 commit comments