Debian Codegraph @

benchmark/main.sml

raw
1 (* Copyright (C) 2013,2014,2019,2022 Matthew Fluet.
2 * Copyright (C) 2009 Matthew Fluet.
3 * Copyright (C) 1999-2007 Henry Cejtin, Matthew Fluet, Suresh
4 * Jagannathan, and Stephen Weeks.
5 * Copyright (C) 1997-2000 NEC Research Institute.
6 *
7 * MLton is released under a HPND-style license.
8 * See the file MLton-LICENSE for details.
9 *)
10
11 structure Main =
12 struct
13
14 type int = Int.t
15
16 fun usage msg =
17 CommandLine.usage {usage = "[-mlkit] [-mlton </path/to/mlton>] [-mosml] [-poly] [-smlnj] bench1 bench2 ...",
18 msg = msg}
19
20 val doOnce = ref false
21 val doWiki = ref false
22 val runArgs : string list ref = ref []
23
24 fun withInput (file, f: unit -> 'a): 'a =
25 let
26 open FileDesc
27 val inFd =
28 let
29 open Pervasive.Posix.FileSys
30 in
31 openf (file, O_RDONLY, O.flags [])
32 end
33 in
34 Exn.finally
35 (fn () => FileDesc.fluidLet (FileDesc.stdin, inFd, f),
36 fn () => FileDesc.close inFd)
37 end
38
39 fun ignoreOutput f =
40 let
41 val nullFd =
42 let
43 open Pervasive.Posix.FileSys
44 in
45 openf ("/dev/null", O_WRONLY, O.flags [])
46 end
47 open FileDesc
48 in
49 Exn.finally
50 (fn () => fluidLet (stderr, nullFd, fn () =>
51 fluidLet (stdout, nullFd, f)),
52 fn () => close nullFd)
53 end
54
55 datatype command =
56 Explicit of {args: string list,
57 com: string}
58 | Shell of string list
59
60 fun timeIt ca =
61 Process.time
62 (fn () =>
63 case ca of
64 Explicit {args, com} =>
65 Process.waitChildPid (Process.spawnp {file = com, args = com :: args})
66 | Shell ss => List.foreach (ss, Process.system))
67
68 local
69 val trialTime = Time.seconds (IntInf.fromInt 60)
70 in
71 fun timeCall (com, args): real =
72 let
73 fun doit ac =
74 let
75 val {user, system} = timeIt (Explicit {args = args, com = com})
76 val op + = Time.+
77 in ac + user + system
78 end
79 fun loop (n, ac: Time.t): real =
80 if Time.> (ac, trialTime)
81 then Time.toReal ac / Real.fromInt n
82 else loop (n + 1, doit ac)
83 in
84 if !doOnce
85 then Time.toReal (doit Time.zero)
86 else loop (0, Time.zero)
87 end
88 end
89
90 val benchCounts: (string * int) list =
91 ("barnes-hut", 32768):: (* 41.85 sec *)
92 ("boyer", 12288):: (* 36.04 sec *)
93 ("checksum", 12288):: (* 42.48 sec *)
94 ("count-graphs", 12):: (* 30.27 sec *)
95 ("DLXSimulator", 6):: (* 31.83 sec *)
96 ("even-odd", 24):: (* 38.96 sec *)
97 ("fft", 16):: (* 39.63 sec *)
98 ("fib", 32):: (* 40.10 sec *)
99 ("flat-array", 49152):: (* 35.25 sec *)
100 ("hamlet", 384):: (* 45.55 sec *)
101 ("imp-for", 4096):: (* 31.57 sec *)
102 ("knuth-bendix", 3072):: (* 34.40 sec *)
103 ("lexgen", 1536):: (* 41.54 sec *)
104 ("life", 32):: (* 38.71 sec *)
105 ("logic", 256):: (* 33.24 sec *)
106 ("mandelbrot", 6):: (* 35.66 sec *)
107 ("matrix-multiply", 192):: (* 43.54 sec *)
108 ("md5", 12):: (* 34.73 sec *)
109 ("merge", 16384):: (* 33.35 sec *)
110 ("mlyacc", 3072):: (* 34.04 sec *)
111 ("model-elimination", 4):: (* 39.68 sec *)
112 ("mpuz", 128):: (* 39.63 sec *)
113 ("nucleic", 4096):: (* 31.41 sec *)
114 ("output1", 12):: (* 32.92 sec *)
115 ("peek", 192):: (* 36.99 sec *)
116 ("pidigits", 4096):: (* 37.95 sec *)
117 ("psdes-random", 24):: (* 33.80 sec *)
118 ("ratio-regions", 1536):: (* 47.22 sec *)
119 ("ray", 1536):: (* 37.14 sec *)
120 ("raytrace", 96):: (* 33.44 sec *)
121 ("simple", 1024):: (* 36.55 sec *)
122 ("smith-normal-form", 192):: (* 40.96 sec *)
123 ("string-concat", 256):: (* 30.66 sec *)
124 ("tailfib", 512):: (* 37.87 sec *)
125 ("tailmerge", 24576):: (* 42.64 sec *)
126 ("tak", 32):: (* 37.01 sec *)
127 ("tensor", 6):: (* 38.95 sec *)
128 ("tsp", 16):: (* 37.29 sec *)
129 ("tyan", 384):: (* 30.86 sec *)
130 ("vector32-concat", 48):: (* 41.15 sec *)
131 ("vector64-concat", 32):: (* 30.33 sec *)
132 ("vector-rev", 96):: (* 39.46 sec *)
133 ("vliw", 1024):: (* 39.60 sec *)
134 ("wc-input1", 16384):: (* 30.21 sec *)
135 ("wc-scanStream", 32768):: (* 31.67 sec *)
136 ("zebra", 64):: (* 30.04 sec *)
137 ("zern", 16384):: (* 38.98 sec *)
138 nil
139
140 val benchCount =
141 String.memoize
142 (fn s =>
143 case List.peek (benchCounts, fn (b, _) => b = s) of
144 NONE => Error.bug (concat ["no benchCount for ", s])
145 | SOME (_, c) => Int.toString c)
146
147 val default_main = (fn bench => concat ["val _ = Main.doit ", benchCount bench, "\n"])
148
149 local
150 (*
151 * text data bss dec hex filename
152 * 3272995 818052 24120 4115167 3ecadf mlton
153 *)
154 fun size (f: File.t): {text: int, data: int, bss: int} =
155 let
156 val fail = fn () => Process.fail (concat ["size failed on ", f])
157 in
158 File.withTemp
159 (fn sizeRes =>
160 let
161 val _ = Process.system (concat ["size ", f, ">", sizeRes])
162 in
163 File.withIn
164 (sizeRes, fn ins =>
165 case In.lines ins of
166 [_, nums] =>
167 (case String.tokens (nums, Char.isSpace) of
168 text :: data :: bss :: _ =>
169 (case (Int.fromString text,
170 Int.fromString data,
171 Int.fromString bss) of
172 (SOME text, SOME data, SOME bss) =>
173 {text = text, data = data, bss = bss}
174 | _ => fail ())
175 | _ => fail ())
176 | _ => fail ())
177 end)
178 end
179 in
180 fun compileSizeRun {command, exe, doTextPlusData: bool} =
181 Escape.new
182 (fn e =>
183 let
184 val exe = "./" ^ exe
185 val {system, user} = timeIt command
186 handle _ => Escape.escape (e, {compile = NONE,
187 run = NONE,
188 size = NONE})
189 val compile = SOME (Time.toReal (Time.+ (system, user)))
190 val size =
191 if doTextPlusData
192 then
193 let
194 val {text, data, ...} = size exe
195 in SOME (Position.fromInt (text + data))
196 end
197 else SOME (File.size exe)
198 val run =
199 timeCall (exe, !runArgs)
200 handle _ => Escape.escape (e, {compile = compile,
201 run = NONE,
202 size = size})
203 in {compile = compile,
204 run = SOME run,
205 size = size}
206 end)
207 end
208
209 fun batch_ {abbrv, bench} =
210 let
211 val abbrv =
212 String.translate
213 (abbrv, fn c =>
214 if Char.isAlphaNum c
215 then String.fromChar c
216 else "_")
217 in
218 concat [bench, ".", abbrv, ".batch"]
219 end
220
221 fun batch ab =
222 concat [batch_ ab, ".sml"]
223
224 local
225 val next = Counter.generator 0
226 in
227 fun makeMLton commandPattern =
228 case ChoicePattern.expand commandPattern of
229 Result.No m => usage m
230 | Result.Yes cmds =>
231 List.map
232 (cmds, fn cmd =>
233 let
234 val abbrv = "MLton" ^ (Int.toString (next ()))
235 in
236 {name = cmd,
237 abbrv = abbrv,
238 main = default_main,
239 test = (fn {bench} =>
240 let
241 val src = batch {abbrv = abbrv, bench = bench}
242 val exe = String.dropSuffix (src, 4)
243 val cmds = (concat [cmd, " -output ", exe, " ", src])::
244 (*(concat ["strip ", exe])::*)
245 nil
246 in
247 compileSizeRun
248 {command = Shell cmds,
249 exe = exe,
250 doTextPlusData = true}
251 end)}
252 end)
253 end
254
255 fun kitCompile {bench} =
256 let
257 val bargs = {abbrv = "MLKit", bench = bench}
258 val bin = batch_ bargs
259 in compileSizeRun
260 {command = Explicit {args = ["-o", bin, batch bargs],
261 com = "mlkit"},
262 exe = bin,
263 doTextPlusData = true}
264 end
265
266 fun mosmlCompile {bench} =
267 let
268 val bargs = {abbrv = "Moscow ML", bench = bench}
269 val bin = batch_ bargs
270 in compileSizeRun
271 {command = Explicit {args = ["-orthodox", "-standalone", "-toplevel",
272 "-o", bin, batch bargs],
273 com = "mosmlc"},
274 exe = bin,
275 doTextPlusData = false}
276 end
277
278
279 val njSuffix =
280 Promise.delay
281 (fn () =>
282 let
283 val sml = "sml"
284 val suffix =
285 File.withTemp
286 (fn tmp =>
287 (File.withTempOut
288 (fn output =>
289 Out.output
290 (output, concat ["val tmp = TextIO.openOut(\"", tmp, "\");\n",
291 "val _ = TextIO.output(tmp, SMLofNJ.SysInfo.getHeapSuffix());\n",
292 "val _ = TextIO.closeOut(tmp);\n"]),
293 fn input =>
294 withInput
295 (input, fn () =>
296 Process.waitChildPid (Process.spawnp {file = sml, args = [sml]})))
297 ; In.withClose (In.openIn tmp, In.inputAll)))
298 in
299 suffix
300 end)
301
302 fun njCompile {bench} =
303 Escape.new
304 (fn e =>
305 let
306 (* sml should start SML/NJ *)
307 val sml = "sml"
308 val {system, user} =
309 File.withTempOut
310 (fn out =>
311 (Out.output
312 (out, "local\nval _ = SMLofNJ.Internals.GC.messages false\n")
313 ; File.outputContents (concat [bench, ".sml"], out)
314 ; (Out.output
315 (out,
316 concat
317 ["in val _ = SMLofNJ.exportFn (\"", bench,
318 "\", fn _ => (Main.doit ", benchCount bench,
319 "; OS.Process.success))\nend\n"]
320 ))),
321 fn input => withInput (input, fn () => timeIt (Explicit {args = [],
322 com = sml})))
323 handle _ => Escape.escape (e, {compile = NONE,
324 run = NONE,
325 size = NONE})
326 val suffix = Promise.force njSuffix
327 val heap = concat [bench, ".", suffix]
328 in
329 if not (File.doesExist heap)
330 then {compile = NONE,
331 run = NONE,
332 size = NONE}
333 else
334 let
335 val compile = Time.toReal (Time.+ (user, system))
336 val size = SOME (File.size heap)
337 val run =
338 timeCall (sml, [concat ["@SMLload=", heap]])
339 handle _ => Escape.escape (e, {compile = SOME compile,
340 run = NONE,
341 size = size})
342 in {compile = SOME compile,
343 run = SOME run,
344 size = size}
345 end
346 end)
347
348 fun polyCompile {bench} =
349 let
350 val bargs = {abbrv = "Poly/ML", bench = bench}
351 val bin = batch_ bargs
352 in compileSizeRun
353 {command = Explicit {args = [batch bargs, "-o", bin],
354 com = "polyc"},
355 exe = bin,
356 doTextPlusData = false}
357 end
358
359 type 'a data = {bench: string,
360 compiler: string,
361 value: 'a} list
362
363 fun main (_, args) =
364 let
365 val compilers: {name: string,
366 abbrv: string,
367 main: string -> string,
368 test: {bench: File.t} -> {compile: real option,
369 run: real option,
370 size: Position.int option}} list ref
371 = ref []
372 fun pushCompiler compiler = List.push(compilers, compiler)
373 fun pushCompilers compilers' = compilers := (List.rev compilers') @ (!compilers)
374
375 fun setData (switch, data, str) =
376 let
377 fun die () = usage (concat ["invalid -", switch, " argument: ", str])
378 open Regexp
379 val numSave = Save.new ()
380 val regexpSave = Save.new ()
381 val re = seq [save (star digit, numSave),
382 char #",",
383 save (star any, regexpSave)]
384 val reC = compileDFA re
385 in
386 case Compiled.matchAll (reC, str) of
387 NONE => die ()
388 | SOME match =>
389 let
390 val num = Match.lookupString (match, numSave)
391 val num = case Int.fromString num of
392 NONE => die ()
393 | SOME num => num
394 val regexp = Match.lookupString (match, regexpSave)
395 val (regexp, saves) =
396 case Regexp.fromString regexp of
397 NONE => die ()
398 | SOME regexp => regexp
399 val save = if 0 <= num andalso num < Vector.length saves
400 then Vector.sub (saves, num)
401 else die ()
402 val regexpC = compileDFA regexp
403 fun doit s =
404 Option.map
405 (Compiled.matchAll (regexpC, s),
406 fn match => Match.lookupString (match, save))
407 in
408 data := SOME (str, doit)
409 end
410 end
411 val outData : (string * (string -> string option)) option ref = ref NONE
412 val setOutData = fn str => setData ("out", outData, str)
413 val errData : (string * (string -> string option)) option ref = ref NONE
414 val setErrData = fn str => setData ("err", errData, str)
415 (* Set the stack limit to its max, since mlkit segfaults on some benchmarks
416 * otherwise.
417 *)
418 val _ =
419 let
420 open MLton.Platform.OS
421 in
422 if host = Linux
423 then
424 let
425 open MLton.Rlimit
426 val {hard, ...} = get stackSize
427 in
428 set (stackSize, {hard = hard, soft = hard})
429 end
430 else ()
431 end
432 local
433 open Popt
434 in
435 val res =
436 parse
437 {switches = args,
438 opts = [("args",
439 SpaceString
440 (fn args =>
441 runArgs := String.tokens (args, Char.isSpace))),
442 ("err", SpaceString setErrData),
443 ("mlkit",
444 None (fn () => pushCompiler
445 {name = "MLKit",
446 abbrv = "MLKit",
447 main = default_main,
448 test = kitCompile})),
449 ("mosml",
450 None (fn () => pushCompiler
451 {name = "Moscow ML",
452 abbrv = "Moscow ML",
453 main = default_main,
454 test = mosmlCompile})),
455 ("mlton",
456 SpaceString (fn arg => pushCompilers
457 (makeMLton arg))),
458 ("once", trueRef doOnce),
459 ("out", SpaceString setOutData),
460 ("poly",
461 None (fn () => pushCompiler
462 {name = "Poly/ML",
463 abbrv = "Poly/ML",
464 main = (fn bench => concat ["fun main _ = Main.doit ", benchCount bench, "\n"]),
465 test = polyCompile})),
466 ("smlnj",
467 None (fn () => pushCompiler
468 {name = "SML/NJ",
469 abbrv = "SML/NJ",
470 main = default_main,
471 test = njCompile})),
472 trace,
473 ("wiki", trueRef doWiki)]}
474 end
475 in
476 case res of
477 Result.No msg => usage msg
478 | Result.Yes benchmarks =>
479 let
480 val compilers = List.rev (!compilers)
481 val base = #abbrv (hd compilers)
482 val _ =
483 let
484 open MLton.Signal
485 in
486 setHandler (Pervasive.Posix.Signal.pipe, Handler.ignore)
487 end
488 fun r2s n r = Real.format (r, Real.Format.fix (SOME n))
489 val i2s = Int.toCommaString
490 val p2s = i2s o Position.toInt
491 val s2s = fn s => s
492 val failures = ref []
493 fun show ({compiles, runs, sizes, errs, outs}, {showAll}) =
494 let
495 val out = Out.standard
496 val _ =
497 List.foreach
498 (compilers, fn {name, abbrv, ...} =>
499 Out.output (out, concat [abbrv, " -- ", name, "\n"]))
500 val _ =
501 case !failures of
502 [] => ()
503 | fs =>
504 Out.output
505 (out,
506 concat ["WARNING: ", base, " failed on: ",
507 concat (List.separate (fs, ", ")),
508 "\n"])
509 fun show (title, data: 'a data, toString, toStringHtml) =
510 let
511 val _ = Out.output (out, concat [title, "\n"])
512 val compilers =
513 List.fold
514 (compilers, [], fn ({name = n, abbrv = a, ...}, ac) =>
515 if showAll
516 orelse List.exists (data, fn {compiler = c', ...} =>
517 a = c')
518 then (n, a) :: ac
519 else ac)
520 val benchmarks =
521 List.fold
522 (benchmarks, [], fn (b, ac) =>
523 if showAll
524 orelse List.exists (data, fn {bench = b', ...} =>
525 b = b')
526 then b :: ac
527 else ac)
528 fun rows toString =
529 ("benchmark"
530 :: List.revMap (compilers, fn (_, a) => a))
531 :: (List.revMap
532 (benchmarks, fn b =>
533 b :: (List.revMap
534 (compilers, fn (_, a) =>
535 case (List.peek
536 (data, fn {bench = b',
537 compiler = c', ...} =>
538 b = b' andalso a = c')) of
539 NONE => "*"
540 | SOME {value = v, ...} =>
541 toString v))))
542 open Justify
543 val () =
544 outputTable
545 (table {columnHeads = NONE,
546 justs = (Left ::
547 List.revMap (compilers,
548 fn _ => Right)),
549 rows = rows toString},
550 out)
551 fun prow ns =
552 let
553 fun p s = Out.output (out, s)
554 in
555 case ns of
556 [] => raise Fail "bug"
557 | b :: ns =>
558 (p "||"
559 ; p b
560 ; List.foreach (ns, fn n =>
561 (p "||"; p n))
562 ; p "||\n")
563 end
564 val _ =
565 if not (!doWiki)
566 then ()
567 else
568 let
569 val rows = rows toStringHtml
570 in
571 prow (hd rows)
572 ; (List.foreach
573 (tl rows,
574 fn [] => raise Fail "bug"
575 | b :: r =>
576 let
577 val b =
578 concat
579 ["[attachment:",
580 b, ".sml ", b, "]"]
581 in
582 prow (b :: r)
583 end))
584 end
585 in
586 ()
587 end
588 val bases = List.keepAll (runs, fn {compiler, ...} =>
589 compiler = base)
590 val ratios =
591 List.fold
592 (runs, [], fn ({bench, compiler, value}, ac) =>
593 if compiler = base andalso not showAll
594 then ac
595 else
596 {bench = bench,
597 compiler = compiler,
598 value =
599 case List.peek (bases, fn {bench = b, ...} =>
600 bench = b) of
601 NONE => ~1.0
602 | SOME {value = v, ...} => value / v} :: ac)
603 val _ = show ("run time ratio", ratios, r2s 2, r2s 1)
604 val _ = show ("size", sizes, p2s, p2s)
605 val _ = show ("compile time", compiles, r2s 2, r2s 2)
606 val _ = show ("run time", runs, r2s 2, r2s 2)
607 val _ = case !outData of
608 NONE => ()
609 | SOME (out, _) =>
610 show (concat ["out: ", out], outs, s2s, s2s)
611 val _ = case !errData of
612 NONE => ()
613 | SOME (err, _) =>
614 show (concat ["err: ", err], errs, s2s, s2s)
615 in ()
616 end
617 val totalFailures = ref []
618 val data =
619 List.fold
620 (benchmarks, {compiles = [], runs = [], sizes = [],
621 outs = [], errs = []},
622 fn (bench, ac) =>
623 let
624 val foundOne = ref false
625 val res =
626 List.fold
627 (compilers, ac, fn ({name, abbrv, main, test},
628 ac as {compiles: real data,
629 runs: real data,
630 sizes: Position.int data,
631 outs: string data,
632 errs: string data}) =>
633 if true
634 then
635 let
636 val _ =
637 File.withOut
638 (batch {abbrv = abbrv, bench = bench}, fn out =>
639 (File.outputContents (concat [bench, ".sml"], out);
640 Out.output (out, (main bench))))
641 (*
642 val outTmpFile =
643 File.tempName {prefix = "tmp", suffix = "out"}
644 val errTmpFile =
645 File.tempName {prefix = "tmp", suffix = "err"}
646 *)
647 val {compile, run, size} =
648 ignoreOutput
649 (fn () => test {bench = bench})
650 val _ =
651 if name = base
652 andalso Option.isNone run
653 then List.push (failures, bench)
654 else ()
655 (*
656 val out =
657 case !outData of
658 NONE => NONE
659 | SOME (_, doit) =>
660 File.foldLines
661 (outTmpFile, NONE, fn (s, v) =>
662 let val s = String.removeTrailing
663 (s, fn c =>
664 Char.equals (c, Char.newline))
665 in
666 case doit s of
667 NONE => v
668 | v => v
669 end)
670 val err =
671 case !errData of
672 NONE => NONE
673 | SOME (_, doit) =>
674 File.foldLines
675 (errTmpFile, NONE, fn (s, v) =>
676 let val s = String.removeTrailing
677 (s, fn c =>
678 Char.equals (c, Char.newline))
679 in
680 case doit s of
681 NONE => v
682 | v => v
683 end)
684 val _ = File.remove outTmpFile
685 val _ = File.remove errTmpFile
686 *)
687 val out = NONE
688 val err = NONE
689 fun add (v, ac) =
690 case v of
691 NONE => ac
692 | SOME v =>
693 (foundOne := true
694 ; {bench = bench,
695 compiler = abbrv,
696 value = v} :: ac)
697 val ac =
698 {compiles = add (compile, compiles),
699 runs = add (run, runs),
700 sizes = add (size, sizes),
701 outs = add (out, outs),
702 errs = add (err, errs)}
703 val _ = show (ac, {showAll = false})
704 val _ = Out.flush Out.standard
705 in
706 ac
707 end
708 else ac)
709 val _ =
710 if !foundOne
711 then ()
712 else List.push (totalFailures, bench)
713 in
714 res
715 end)
716 val _ = show (data, {showAll = true})
717 val totalFailures = !totalFailures
718 val _ =
719 if List.isEmpty totalFailures
720 then ()
721 else (print ("The following benchmarks failed completely.\n")
722 ; List.foreach (totalFailures, fn s =>
723 print (concat [s, "\n"])))
724 in ()
725 end
726 end
727
728 val main = CommandLine.make main
729
730 end