Andy73

vBenchmark Super Experimental

Feb 12th, 2015
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 24.84 KB | None | 0 0
  1. --[[
  2.        ______________________________________
  3.       / | \            |                 |  
  4. _    /  |_/  _       _ |_         _      |  
  5.  \  /   | \ /_\ +-+ /  | | +-+-+ '_\ ,_  |/
  6.   \/    |_/ \_  | | \_ | | | | | (_| | ' |\
  7.  
  8.  
  9. vBenchmark
  10. ==========
  11. An advanced benchmarking
  12. program for CC, good for
  13. comparison of various CC
  14. emulators.
  15.  
  16. version 0.2.5 (or Version (table))
  17. (build number @ /buildn)
  18.  
  19.  
  20. Contact me on the
  21. [CC Forums!](http://computercraft.info/forums2)
  22.  
  23. Made by viluon a.k.a. Andy73
  24. (c) 2015
  25.  
  26. Dev Notes:
  27. ==========
  28. TODO:
  29. --graphs
  30. --DONE:CLI
  31. --Settings
  32. --DONE:organized output (a-z)
  33. --all the tests listed in comments
  34. --DONE:+version in goodbye
  35.  
  36. +50
  37.  
  38. ]]
  39.  
  40. local Version={
  41.     App="0.2.5",
  42.     DebugID="REL",
  43. }
  44.  
  45. local SuicidalMode=false
  46.  
  47. local Args={...}
  48. local args={}
  49. for k,v in pairs(Args) do
  50.     args[k]=v
  51. end
  52.  
  53. local term,colors,window,shell,fs,type,error,tostring,tonumber,unpack,pcall,table,coroutine,string=term,colors,window,shell,fs,type,error,tostring,tonumber,unpack,pcall,table,coroutine,string --speed up!
  54.  
  55. term.redirect(term.native())
  56. local w,h=term.getSize() --screen width and height, used at different places
  57.  
  58. -----startup
  59. term.setBackgroundColor(colors.black)
  60. term.clear()
  61. term.setCursorPos(1,1)
  62.  
  63. local shouldRestart=false
  64.  
  65. local function apicheck(n,p,fex)    --name, paste ID, File EXtension fix TODO: file extension fix (Test.lua),
  66.     if not fs.exists("/"..(fex and n..".lua" or n)) and not _G[n] then
  67.         printError("No "..n.." API found, downloading one...")
  68.         shell.run("pastebin get "..p.." /"..(fex and n..".lua" or n))
  69.         shouldRestart=true
  70.     end
  71.     return true
  72. end
  73.  
  74. apicheck("sha256","P3KBjR3M")
  75. apicheck("aes","DMx8M0LP")
  76. apicheck("crc32","x52gQYWp")
  77. apicheck("json","jK22eUfn")
  78. apicheck("Test","wZbpA1Gy",true)
  79.  
  80. if shouldRestart then
  81.     return shell.run(shell.getRunningProgram(),unpack(Args))
  82. end
  83.  
  84. local libs={
  85.     ["Test.lua"]=dofile,
  86.     ["sha256"]=os.loadAPI,
  87.     ["aes"]=os.loadAPI,
  88.     ["crc32"]=os.loadAPI,
  89.     ["json"]=os.loadAPI,
  90. }
  91. for k,v in pairs(libs) do
  92.     local ok,err=pcall(v,"/"..k)
  93.     if not ok then print(err) sleep(2) end
  94. end
  95.  
  96. pcall(fs.delete,"/.vBenchmarkUpdater.lua")
  97.  
  98. Version.Library=Test.Version
  99.  
  100. --------GENERAL FUNCTIONS AND CLASSES
  101.  
  102. local function s()
  103.     local t=tostring({})
  104.     os.queueEvent(t)
  105.     coroutine.yield(t)
  106. end
  107.  
  108. local function pairsByKeys (t, f)
  109.     local a = {}
  110.     for n in pairs(t) do table.insert(a, n) end
  111.     table.sort(a, f)
  112.     local i = 0         -- iterator variable
  113.     local iter = function ()        -- iterator function
  114.         i = i + 1
  115.         if a[i] == nil then return nil
  116.         else return a[i], t[a[i]]
  117.         end
  118.     end
  119.     return iter
  120. end
  121.  
  122. local Results
  123. local names={
  124. ["ow"]="Optimized write test",
  125. ["uw"]="Unoptimized write test",
  126. ["tb"]="term.blit write test",
  127. ["ct"]="Color swap/rainbow test",
  128. ["lc"]="Line clear speed test",
  129. ["cs"]="Clear speed test",
  130. ["scr"]="Buffer scroll test",
  131. ["aa"]="Anti-aliasing test",
  132. ["hsh"]="SHA256 hash test",
  133. ["aese"]="AES Encryption perf. test",
  134. ["aesd"]="AES Decryption perf. test",
  135. ["tec"]="Table entry creation",
  136. ["ted"]="Table entry deletion",
  137. ["tea"]="Table entry access",
  138. ["dhke"]="Diffie-Hellman key exchange",
  139. ["crc"]="CRC32 hash test",
  140. ["cmpl1"]="Simple compilation",
  141. ["cmpl2"]="Medium compilation",
  142. ["ftw"]="Text file write test",
  143. ["ftr"]="Text file read test",
  144. }
  145. local TaskList={}
  146. for k,v in pairs(names)do
  147.     TaskList[k]=true
  148. end
  149.  
  150. local outputPath="/benchmark.txt"
  151. local maxTime=2 --maximum b. test time in seconds
  152. local maxCalls=10000    --maximum b. test iterations (number of calls)
  153.  
  154.  
  155.  
  156. local function listToTable( str )
  157.     if type(str)~="string" then error("(1)Expected string, got "..type(str),2) end
  158.     if str:sub(#str,#str)~="," then str=str.."," end
  159.     local out={}
  160.     for entry in str:gmatch("(%a+),") do
  161.         table.insert(out,entry)
  162.     end
  163.     return out
  164. end
  165.  
  166. local function help(c)
  167.     local txt=[[
  168.  
  169. Welcome to vBenchmark!
  170.          
  171.     vBenchmark is a complex benchmarking program for ComputerCraft 1.6+, made by viluon (a.k.a. Andy73)
  172.  
  173.     [Usage]
  174.         vBenchmark  -option value   --flag  -option2 list,of,values
  175.        
  176.        
  177.  
  178.         NOTE: Options and flags are executed in the order they're supplied in
  179.            
  180.         <required value> [optional value] (name)
  181.  
  182.         Available options:
  183.         =================
  184.             update (update) updates the program
  185.             =====
  186.             help OR ? OR /? ['light'] (help/usage) displays this page, optionally using black text on white background (this option stops the execution automatically)
  187.             =====
  188.             -o <path> (output) sets the output file to <path>
  189.             =====
  190.             -list [path] (list) lists the names and corresponding codes of available benchmark functions, optionally saving them to [path]
  191.             =====
  192.             -maxtime <seconds> (maximum time limit) sets the time limit per ONE benchmark function to <seconds> - default: 2
  193.             =====
  194.             -maxcalls <calls> (maximum function calls) sets the maximum amount of function calls per ONE benchmark function to <calls>  - default: 10 000
  195.             =====
  196.             -exclude <tests> (exclude) excludes a list of tests from the benchmark, <tests> is a list of test codes
  197.             =====
  198.             -testonly <tests> (test only) sets the test list for the benchmark to <tests>
  199.             =====
  200.  
  201.         Available flags:
  202.         ===============
  203.             --test (test) prints some debug text on the screen
  204.             =====
  205.             --stop (stop) stops the execution of the benchmark
  206.             =====
  207.             --version (version info) displays the version information of the program and used libraries
  208.             =====
  209.             --SUICIDE (suicidal mode) Enables the suicidal mode:
  210.                 Suicidal mode is intended for debugging, evaluating and precision testing of CC emulators or SINGLEPLAYER CC.
  211.                 Do NOT use the suicidal benchmark in multiplayer!!! Suicidal benchmark does not yield to produce the most relevant results.
  212.                 As such, it should NOT be used for regular benchmarking. The suicidal mode can corrupt files and do IRREVERSIBLE HARM!!!
  213.                 Use at your own risk.
  214.             =====
  215.             --safe (safe mode) enables safety features:
  216.                 -output file backup
  217.                 -visible error reports  - launches the benchmark in a temporary handler (/.vBenchmarkSafe) that pauses after crashing => errors visible
  218.                 -does not intersect with suicidal mode]]
  219.             --TODO  -include <paths> include list of custom tests loaded from <paths>
  220.     term.setBackgroundColor(c and colors.white or colors.black)
  221.     term.setTextColor(c and colors.black or colors.white)
  222.     term.clear()
  223.     term.setCursorPos(1,1)
  224.     textutils.pagedPrint(txt)
  225. end
  226.  
  227.  
  228.  
  229. local flags={
  230.     ["test"]=function()
  231.         print"This is a test"
  232.         sleep(3)
  233.     end,
  234.     ["stop"]=function()
  235.         error()
  236.     end,
  237.     ["version"]=function()
  238.         print(textutils.serialize(Version))
  239.     end,
  240.     ["suicide"]=function()
  241.         SuicidalMode=true
  242.     end,
  243.     ["safe"]=function()
  244.         if fs.exists(outputPath) then
  245.             local bkpPath,i=".bkp1",2
  246.             while fs.exists(outputPath..bkpPath) do
  247.                 bkpPath=".bkp"..i
  248.                 i=i+1
  249.             end
  250.             local ok,err=pcall(fs.copy,outputPath,outputPath..bkpPath)
  251.             if not ok then
  252.                 print"[ERROR] Failed to create backup"
  253.                 print(err)
  254.                 print"Press ENTER to exit"
  255.                 read" "
  256.             end
  257.         end
  258.         local f=fs.open("/.vBenchmarkSafe","w")
  259.         if not f then print"[ERROR] Failed to open file for writing: /.vBenchmarkSafe" print(e) sleep(5) error() end
  260. f.write([[
  261. print"Launching vBenchmark in safe mode"
  262. sleep(2)
  263. local path,args="]]..shell.getRunningProgram()..[[",{...}
  264. local f=fs.open(path,"r")
  265. local fn=f.readAll()
  266. f.close()
  267. fn=loadstring(fn,"vBenchmark [SAFE MODE]")
  268. if not fn then error("Failed to execute safe mode: file is corrupt!",0) end
  269. setfenv(fn,setmetatable({shell=setmetatable({getRunningProgram=function()return path end},{__index=_G.shell})},{__index=_G}))
  270. local o,e=pcall(fn,unpack(args))
  271. if not o then
  272.     printError"vBenchmark has crashed."
  273.     print""
  274.     print(e)
  275.     print"Enter to continue..."
  276.     read" "
  277. end
  278. return true
  279. ]])
  280.         f.close()
  281.         local n=Args
  282.         for k,v in pairs(n) do
  283.             if v:lower()=="--safe" then table.remove(n,k) end
  284.             if #n<1 or #n==k then break end
  285.         end
  286.         shell.run("/.vBenchmarkSafe",unpack(n))
  287.         error()
  288.     end,
  289. }
  290. local options={
  291.     ["o"]={
  292.         function(path)
  293.             if type(path)~="string" then error("Expected string as output path, got "..type(path),0) end
  294.             outputPath=path
  295.         end,
  296.         1,  --max arguments
  297.         1,  --min arguments
  298.     },
  299.     ["list"]={
  300.         function(path)
  301.             for k,v in pairs(names) do
  302.                 print(v.."="..k)
  303.             end
  304.             if type(path)=="string" then
  305.                 if fs.exists(path) then
  306.                     local f=fs.open(path,"w")
  307.                     f.write(textutils.serialize(names))
  308.                     f.close()
  309.                 end
  310.             end
  311.         end,
  312.         1,
  313.         0,
  314.     },
  315.     ["maxcalls"]={
  316.         function(c)
  317.             if not tonumber(c) then error("Expected number for the maximum amount of calls, got "..type(c),0) end
  318.             maxCalls=tonumber(c)
  319.         end,
  320.         1,
  321.         1,
  322.     },
  323.     ["maxtime"]={
  324.         function(c)
  325.             if not tonumber(c) then error("Expected number for the maximum time, got "..type(c),0) end
  326.             maxTime=tonumber(c)
  327.         end,
  328.         1,
  329.         1,
  330.     },
  331.     ["testonly"]={
  332.         function(list)
  333.             if type(list)~="string" then error("Expected string as a list of tests, got "..type(list),0) end
  334.             TaskList={}
  335.             for k,v in pairs(listToTable(list)) do
  336.                 TaskList[v]=true
  337.             end
  338.         end,
  339.         1,
  340.         1,
  341.     },
  342.     ["exclude"]={
  343.         function(list)
  344.             for k,v in pairs(listToTable(list)) do
  345.                 TaskList[v]=false
  346.             end
  347.         end,
  348.         1,
  349.         1,
  350.     },
  351. }
  352. for i,v in pairs(args) do
  353.     if v:sub(1,2)=="--" then
  354.         if not flags[v:sub(3,#v):lower()] then print("Hint: use '"..shell.getRunningProgram().." help' to see the proper usage")error("Unknown flag: "..v:sub(3,#v),0) end
  355.         flags[v:sub(3,#v):lower()]()
  356.  
  357.     elseif v:sub(1,1)=="-" then
  358.         if not options[v:sub(2,#v):lower()] then print("Hint: use '"..shell.getRunningProgram().." help' to see the proper usage")error("Unknown option: "..v:sub(2,#v),0) end
  359.         local arg={}
  360.  
  361.         for ii=i+1,i+options[v:sub(2,#v):lower()][2] do
  362.             if not args[ii] then break end
  363.             if args[ii]:sub(1,1)=="-" then break end    --if the argument starts with "-" then break end    --and ii-i>options[v:sub(2,#v):lower()][3] and minimum number of arguments has already been reached
  364.             arg[#arg+1]=args[ii]
  365.             args[ii]=nil
  366.         end
  367.  
  368.         options[v:sub(2,#v):lower()][1](unpack(arg))
  369.  
  370.     elseif v:lower()=="help" or v=="?" or v=="/?" then
  371.         if args[i+1]=="light" then return help(true) end
  372.  
  373.         return help()
  374.     elseif v:lower()=="update" then
  375.         local u=fs.open("/.vBenchmarkUpdater.lua","w")
  376.         u.write("shell.run'rm "..shell.getRunningProgram().."'shell.run'pastebin get nCEk57MH "..shell.getRunningProgram().."'print'Update complete'sleep(3)return shell.run'"..shell.getRunningProgram().."    --stop'")
  377.         u.close()
  378.  
  379.         return shell.run"/.vBenchmarkUpdater.lua"
  380.     end
  381. end
  382.  
  383. Test.SetTaskList(TaskList)
  384.  
  385. ---------BENCHMARK FUNCTIONS
  386. local function benchmarkGraphics()  --graphical operations (both term and graphics related calculations)
  387.     ----text
  388.     --------Optimized write
  389.     local function fill(c,bc,ch)    --color, bg color, char
  390.         term.setBackgroundColor(bc or colors.black)
  391.         term.setTextColor(c or colors.white)
  392.         term.clear()
  393.         for y=1,h do
  394.             term.setCursorPos(1,y)
  395.             term.write(string.rep(ch or "X",w))
  396.         end
  397.     end
  398.     local ow=Test.New("ow",nil,maxCalls,maxTime,true,fill)  --ow=optimized write, no group set (nil)->graphics, maxCalls max calls, maxTime maximum total benchmark time, true->yield, 'fill' function to benchmark
  399.     ow.Run()
  400.  
  401.     --------Unoptimized write
  402.     local function fillUnoptimized(c,bc,ch)
  403.         term.setBackgroundColor(bc or colors.black)
  404.         term.setTextColor(c or colors.white)
  405.         term.clear()
  406.         for y=1,h do
  407.             for x=1,w do
  408.                 term.setCursorPos(x,y)
  409.                 term.write(ch or "X")
  410.             end
  411.         end
  412.     end
  413.     local uw=Test.New("uw",nil,maxCalls,maxTime,true,fillUnoptimized)
  414.     uw.Run()
  415.  
  416.     --------term.blit test
  417.     if term.blit then
  418.         local blitText,blitBackground,blitColor=string.rep("7",w),string.rep("0",w),string.rep("f",w)
  419.    
  420.         local function termBlitTest()
  421.             for y=1,h do
  422.                 term.setCursorPos(1,y)
  423.                 term.blit(blitText,blitBackground,blitColor)
  424.             end
  425.         end
  426.    
  427.        
  428.         local tb=Test.New("tb",nil,maxCalls,maxTime,true,termBlitTest)
  429.         tb.Run()
  430.     end
  431.  
  432.     --------Color test
  433.     local function testColor()
  434.         for c=0,15 do
  435.             term.setBackgroundColor(2^c)
  436.             term.clear()
  437.         end
  438.     end
  439.     local ct=Test.New("ct",nil,maxCalls,maxTime,true,testColor)
  440.     ct.Run()
  441.     --------Line clear
  442.     local function lineClear(c)
  443.      term.setBackgroundColor(c or colors.black)
  444.         for y=1,h do
  445.          term.setCursorPos(1,y)
  446.          term.clearLine()
  447.         end
  448.     end
  449.     local lc=Test.New("lc",nil,maxCalls,maxTime,true,lineClear)
  450.     lc.Run()
  451.    
  452.     --------Clear
  453.     term.setBackgroundColor(colors.black)
  454.     local clear=term.clear
  455.     local cs=Test.New("cs",nil,maxCalls,maxTime,true,clear) --TODO/WARN: supply just the term.clear() function?
  456.     cs.Run()
  457.    
  458.     --------Scroll
  459.     local function scroll()
  460.         fill()  --TODO any arguments?
  461.         for y=1,h do
  462.          term.scroll(1)
  463.         end
  464.     end
  465.     local scr=Test.New("scr",nil,maxCalls,maxTime,true,scroll)
  466.     scr.Run()
  467.  
  468.     ----2D graphics
  469.     -------Anti-Aliasing
  470.     local pixelWithAlpha = function(x,y,a)  -- Pseudo Alpha channel. Only works with black background (for obvious reasons)
  471.        
  472.         alphaStep = 255 / 4
  473.        
  474.         if a > 255  - alphaStep then
  475.             term.setBackgroundColor(colors.white)
  476.         elseif a > 255  - alphaStep * 2 then
  477.             term.setBackgroundColor(colors.lightGray)
  478.         elseif a > 255  - alphaStep * 3 then
  479.             term.setBackgroundColor(colors.gray)
  480.         else
  481.             term.setBackgroundColor(colors.black)
  482.             return
  483.         end
  484.        
  485.         term.setCursorPos(x,y)
  486.         term.write(" ")
  487.     end
  488.     local aaLine = function(x0, y0, x1, y1)
  489.    
  490.         dx = math.abs(x1-x0)
  491.         if x0<x1 then sx = 1 else sx =  -1 end
  492.         dy = math.abs(y1-y0)
  493.         if y0<y1 then sy = 1 else sy =  -1 end
  494.        
  495.         err = dx-dy              
  496.        
  497.         if dx + dy == 0 then
  498.             ed = 1
  499.         else
  500.             ed = math.sqrt(dx*dx+dy*dy)
  501.         end
  502.        
  503.         while true do                                    
  504.             pixelWithAlpha(x0,y0, 255   - (255 * math.abs(err-dx+dy)/ed));
  505.             e2 = err
  506.             x2 = x0
  507.             if (2*e2 >= -dx) then                        
  508.                 if (x0 == x1) then break end
  509.                 if (e2+dy < ed) then pixelWithAlpha(x0,y0+sy, 255   - (255*(e2+dy)/ed)) end
  510.                 err = err   - dy;
  511.                 x0 = x0 + sx;
  512.             end
  513.             if (2*e2 <= dy) then                                   
  514.                 if (y0 == y1) then break end
  515.                 if (dx-e2 < ed) then pixelWithAlpha(x2+sx,y0, 255   - (255*(dx-e2)/ed)) end
  516.                 err = err + dx;
  517.                 y0 = y0 + sy;
  518.             end
  519.         end
  520.     end
  521.    
  522.     local w1,h1=math.floor(w/4),math.floor(h/2)
  523.  
  524.     local function aaTest()
  525.         local minX,minY=1,1
  526.         local maxX,maxY=15,15
  527.         local x1,y1,x2,y2=minX,minY,minX+1,minY+1
  528.         return function()
  529.             aaLine(x1,y1,x2,y2)
  530.             if x2>maxX then x2=minX y2=y2+1
  531.             elseif y2>maxY then --[[y2=minY y1=y1+1 end?]]
  532.             elseif x1>maxX then x1=minX y1=y1+1
  533.             elseif y1>maxY then y1=minY x2=x2+1
  534.             else x1=x1+1 end
  535.         end
  536.     end
  537.  
  538.     local aa = Test.New("aa",nil,maxCalls,maxTime,true,aaTest())
  539.     aa.Run()
  540.  
  541.     ----3D graphics (TODO)
  542.    
  543.    
  544.    
  545. end
  546.  
  547.  
  548. local function benchmarkMath()  --mathematical operations
  549.     -------SHA256 Hashing
  550.  local l=256
  551.  local str=""
  552.  for i=1,l do
  553.     str=str..
  554.     string.char(math.random(128))
  555.  end
  556.  local sha=sha256.sha256
  557.  local hsh=Test.New("hsh","Math",maxCalls,maxTime,true,sha,str)
  558.  hsh.Run()
  559.     -------CRC32 Hashing
  560.  
  561.  local crch=crc32.Hash
  562.     --local crc=Test.New("crc","Math",maxCalls,maxTime,true,crch,str)
  563.     --crc.Run()
  564.  
  565.     -------AES Encryption
  566.  local enc,ey,didFinish=false
  567.  local function aesEncrypt(k,l)
  568.     local key=""
  569.     local str=""
  570.     for i=1,k do
  571.         key=key.."b"
  572.     end
  573.     for i=1,l do
  574.         str=str..string.char(math.random(128))
  575.     end
  576.     enc=aes.encrypt(key,str)
  577.     ey=key
  578.     didFinish=true
  579.  end
  580.  local aese=Test.New("aese","Math",maxCalls,maxTime,true,aesEncrypt,32,2048)
  581.  aese.Run()
  582.     -------AES Decryption
  583.  local aesDecrypt=aes.decrypt
  584.  if didFinish then
  585.      local aesd=Test.New("aesd","Math",maxCalls,maxTime,true,aesDecrypt,ey,enc)
  586.      aesd.Run()
  587.  end
  588.     -------Diffie-Hellman Key Exchange (by Anavrins)
  589.  local function dfhlKeyEx()
  590.      local function modexp(remainder,exponent,modulo)
  591.          for i=1,exponent-1 do
  592.              remainder=remainder*remainder
  593.              if remainder>=modulo then
  594.                 remainder=remainder%modulo
  595.              end
  596.          end
  597.          return remainder
  598.      end
  599.      local public_base,public_primeMod=11,625210769
  600.      local alice_secret=math.random(100000,999999)
  601.      local bob_secret=math.random(100000,999999)
  602.  
  603.      local alice_public=modexp(public_base,alice_secret,public_primeMod)
  604.      local bob_public=modexp(public_base,bob_secret,public_primeMod)
  605.  
  606.      modexp(bob_public,alice_secret,public_primeMod)
  607.      modexp(alice_public,bob_secret,public_primeMod)
  608.  end
  609.  local dhke=Test.New("dhke","Math",maxCalls,maxTime,true,dfhlKeyEx)
  610.  dhke.Run()
  611.     -------Compilation test 1
  612.  local function cmpl1()
  613.     local code=[[do end]]
  614.     loadstring(code)
  615.  end
  616.  local cmpl1=Test.New("cmpl1","Math",maxCalls,maxTime,true,cmpl1)
  617.  cmpl1.Run()
  618.     -------Compilation test 2
  619.  local function cmpl2()
  620.     local code=[[local function asd()
  621.     while true do end
  622. end
  623. for i=1,10 do
  624.     print(i)
  625. end
  626. return _G.x or asd]]
  627.     loadstring(code)
  628.  end
  629.  local cmpl2=Test.New("cmpl2","Math",maxCalls,maxTime,true,cmpl2)
  630.  cmpl2.Run()
  631.  
  632.  
  633.     -------Goniometry
  634.  local function gnm()
  635.    
  636.  end
  637. end
  638.  
  639. local function benchmarkPeripherals()   --peripheral benchmark (whatever there is available is benchmarked :D)
  640.  
  641. end
  642.  
  643.  
  644. local function benchmarkFilesystem()    --filesystem related tests
  645.     local fw=fs.open("/tmp","w")
  646.     local dummyText1=string.rep("a",128)
  647.     local dummyText2=string.rep("b",128)
  648.     local i=1
  649.  
  650.     local function textWrite()
  651.         fw.write(i%2==0 and dummyText1 or dummyText2)
  652.         fw.flush()
  653.         i=i+1
  654.     end
  655.  
  656.     local ftw=Test.New("ftw","File System",maxCalls,maxTime,true,textWrite)
  657.     ftw.Run()
  658.  
  659.     fw.close()
  660.     fs.delete("/tmp")
  661.     i=nil
  662.  
  663.  
  664.     local function textRead()
  665.         local fr=fs.open("/rom/apis/gps","r")
  666.         fr.readAll()
  667.         fr.close()
  668.     end
  669.  
  670.     local ftr=Test.New("ftr","File System",maxCalls,maxTime,true,textRead)
  671.     ftr.Run()
  672.  
  673. end
  674.  
  675.  
  676. local function scanForAnomalies()   --scan for anomalies (like LOVE2D Lua mathematical bugs, bit lib etc)
  677.  
  678. end
  679.  
  680. local function benchmarkMemoryAllocation()  --memory allocation
  681.  local function newEntry()
  682.      local t={} --table for allocation entries
  683.      for i=1,40000 do
  684.         t[#t+1]=true
  685.      end
  686.      t=nil
  687.  end
  688.  local tec=Test.New("tec","Memory Allocation",maxCalls,maxTime,true,newEntry)
  689.  tec.Run()
  690.  local function delEntry()
  691.      local t={}
  692.      for i=1,40000 do
  693.          t[#t+1]=true
  694.      end
  695.      for i,v in ipairs(t) do
  696.          t[i]=nil
  697.      end
  698.      t=nil
  699.  end
  700.  local ted=Test.New("ted","Memory Allocation",maxCalls,maxTime,true,delEntry)
  701.  ted.Run()
  702.  local function accEntry()
  703.      local t={true}
  704.      local _=false
  705.      for i=1,40000 do
  706.          _=t[1]
  707.      end
  708.  end
  709.  local tea=Test.New("tea","Memory Allocation",maxCalls,maxTime,true,accEntry)
  710.  tea.Run()
  711. end
  712.  
  713. ----------------------
  714. local wins,index={},1   --wins=pages
  715. wins[1]=window.create(term.native(),1,1,w,h-5,true)
  716. local function hideWins()
  717.     for i,v in pairs(wins) do
  718.         wins[i].setVisible(false)
  719.     end
  720. end
  721.  
  722. local function displayResults() --display results
  723.     Results=Test.GetResults()
  724.     local last
  725.     if fs.exists(outputPath) then
  726.         local f=fs.open(outputPath,"r")
  727.         last=f.readAll()
  728.         f.close()
  729.         last=textutils.unserialize(last)
  730.         if not last then
  731.             local pth=outputPath.."-unsupported.txt"
  732.             local i=1
  733.             while fs.exists(pth) do
  734.                 pth=outputPath.."-unsupported"..i..".txt"
  735.                 i=i+1
  736.             end
  737.             fs.move(outputPath,pth)
  738.         end
  739.         Results["Last"]=last
  740.     end
  741.  
  742.     term.setBackgroundColor(colors.black)
  743.     term.setTextColor(colors.white)
  744.     term.clear()
  745.     term.setCursorPos(1,1)
  746.     local groups={}
  747.     for k,v in pairs(Results) do
  748.         if k~="Last" and k~="Version" and k~="Median" then  --median for future upgrade
  749.             if not groups[v["g"]] then groups[v["g"]]={} end
  750.             table.insert(groups[v["g"]],k)
  751.         end
  752.     end
  753.    
  754.     for g,n in pairs(groups)do
  755.         term.setTextColor(colors.yellow)
  756.         print(g)
  757.         --using pairs by KEYS not values => swap n so that keys are actual names and values are the original Results subtables
  758.         local list={}
  759.  
  760.         for k,v in pairs(n) do
  761.             list[names[v]]=v
  762.         end
  763.  
  764.         for name,v in pairsByKeys(list)do
  765.             if TaskList[v] then
  766.                 local mark=(Results[v]["mark"])
  767.  
  768.                 -- safe check (no nil access attempts hopefully) for compatible Matrix version
  769.                 local lastMark=
  770.                 ((last and last[v] and type(last[v]["mark"])=="number" and
  771.                     (last.Version and (last.Version.Library and (Test.Version and (last.Version.Library.Matrix==Test.Version.Matrix)))))
  772.                 and last[v]["mark"] or false)   --lastMark will either be last[v]["mark"] or false, depending on whether the last test was successful.
  773.                 -- I know, it looks horrible, sorry. The code is kinda simple though, so it shouldn't be too hard to figure out what's going on.
  774.  
  775.                 term.setTextColor(colors.white)
  776.                 term.write(" "..name..":"..string.rep(" ",w-#(name..math.floor(mark)..(lastMark and math.floor(lastMark) or ""))-(lastMark and 7 or 2)))
  777.                 term.setTextColor(colors.lightGray)
  778.                 term.write(math.floor(mark))
  779.  
  780.                 if lastMark then
  781.                     term.setTextColor(lastMark>mark and colors.red or colors.lime)
  782.                     term.write(" "..(lastMark>mark and "v" or "^"))
  783.                     term.setTextColor(colors.lightGray)
  784.                     print(" ("..math.floor(lastMark)..")")
  785.                 else
  786.                     print()
  787.                 end
  788.  
  789.                 local _x,_y=term.getCursorPos()
  790.                 if _y>h-8 then  --9 for safe end (no scrolling)
  791.                     wins[#wins+1]=window.create(term.native(),1,1,w,h-5,false)
  792.                     term.redirect(wins[#wins])
  793.                 end
  794.  
  795.             end
  796.         end
  797.     end
  798.     term.redirect(term.native())
  799. end
  800.  
  801. local function render()
  802.     hideWins()
  803.     wins[index].setVisible(true)
  804.     wins[index].redraw()
  805.     local _x,_y=term.getCursorPos()
  806.  
  807.     term.setBackgroundColor(colors.black)
  808.     term.setTextColor(colors.gray)
  809.     term.setCursorPos(w-10,h-5)
  810.  
  811.     term.write("page ")
  812.     term.setTextColor(colors.lightGray)
  813.     term.write(index.."/"..#wins.."  ")--spaces to clean if #wins>10
  814.     term.setCursorPos(_x,_y)
  815. end
  816.  
  817. ----MAIN CODE
  818.  
  819. local function run()
  820.     benchmarkGraphics()
  821.     benchmarkMath()
  822.     benchmarkPeripherals()
  823.     benchmarkFilesystem()
  824.     scanForAnomalies()
  825.     benchmarkMemoryAllocation()
  826.     --TODO: CC API benchmark (parallel, textutils, etc)
  827.  
  828.     term.setBackgroundColor(colors.black)
  829.     term.clear()
  830. end
  831.  
  832.  
  833. run()
  834.  
  835. term.redirect(wins[1])
  836. displayResults()
  837.  
  838. term.setCursorPos(w/2-5,h-3)
  839. term.setTextColor(colors.gray)
  840. term.write"Loading..."
  841. term.setTextColor(colors.white)
  842. term.setCursorPos(1,h-5)
  843.  
  844. local ip="''"
  845.  
  846. if http then
  847.     local h=http.get("http://acos.bluefile.cz/Utilities/Online/ip.php")
  848.     if h then
  849.         ip=h.readAll()
  850.         h.close()
  851.     end
  852. end
  853.  
  854. ip=textutils.unserialize(ip)
  855.  
  856. local selfie=fs.open(shell.getRunningProgram(),"r")
  857. local c=selfie.readAll()
  858. selfie.close()
  859. Version.Hash=sha256.sha256(c)
  860.  
  861. Version.Fingerprint=sha256.sha256(Version.Hash.."Fingerprint"..os.getComputerID()..ip)
  862. Results["Version"]=Version
  863.  
  864. local save=fs.open(outputPath,"w")
  865. save.write("--viluon's Ultimate Benchmark output, os.time()="..os.time()..", os.day()="..os.day().."\n\n")
  866. save.write(textutils.serialize(Results))
  867. s()
  868. save.close()
  869. local r,l=0,Results.Last
  870. while true do
  871.     r=r+1
  872.     if l==nil then break end
  873.     l=(l and l.Last or nil) --first run fix
  874. end
  875.  
  876. print""
  877. print("Total runs:"..r)
  878. print("Results were logged (see "..outputPath.."). Would you like to re-run the benchmark now?")
  879. print""
  880. term.setBackgroundColor(colors.green)
  881. term.setTextColor(colors.white)
  882. term.write(string.rep(" ",((w/2)/2)-4).."[Re-run]"..string.rep(" ",((w/2)/2)-3))
  883. term.setBackgroundColor(colors.red)
  884. term.setTextColor(colors.black)
  885. term.write(string.rep(" ",((w/2)/2)-3).."[Exit]"..string.rep(" ",((w/2)/2)-1))
  886.  
  887. local rerun=false
  888.  
  889. while true do
  890.     render()
  891.     local ev={coroutine.yield()}
  892.     if ev[1]=="mouse_scroll" then
  893.         index=index+ev[2]
  894.     elseif ev[1]=="mouse_click" and ev[4]==h then
  895.         if ev[3]<w/2 then       --rerun
  896.             rerun=true break
  897.         else                        --exit
  898.             local lines={
  899.                 "       ______________________________________",
  900.                 "      / | \\            |                 |  ",
  901.                 "_    /  |_/  _       _ |_         _      |  ",
  902.                 " \\  /   | \\ /_\\ +-+ /  | | +-+-+ '_\\ ,_  |/ ",
  903.                 "  \\/    |_/ \\_  | | \\_ | | | | | (_| | ' |\\ "
  904.             }
  905.  
  906.             local w,h=term.getSize()
  907.             local X=w/2
  908.             local win=window.create(term.native(),X,1,#lines[1],5,true)
  909.  
  910.             term.setBackgroundColor(colors.black)
  911.             term.clear()
  912.             term.setCursorPos(2,6)
  913.             term.write"(c) "
  914.             term.setTextColor(colors.yellow)
  915.             term.write"viluon"
  916.             term.setTextColor(colors.white)
  917.             term.write" 2015"
  918.            
  919.  
  920.             term.redirect(win)
  921.  
  922.             term.setTextColor(colors.yellow)
  923.  
  924.  
  925.             for i,v in ipairs(lines) do
  926.                 term.setCursorPos(1,i)
  927.                 term.write(v:sub(1,6))
  928.             end
  929.  
  930.             term.setTextColor(colors.white)
  931.             term.setCursorPos(1,3)
  932.             term.write"_"
  933.  
  934.             for i=6,#lines[1] do
  935.                 for k,v in ipairs(lines) do
  936.                     term.setCursorPos(i,k)
  937.                     term.write(v:sub(i,i))
  938.                 end
  939.                 X=X-((w/2-2)/(#lines[1]-6))
  940.                 win.reposition(X,1)
  941.                 sleep(0)
  942.             end
  943.             term.redirect(term.native())
  944.             term.setCursorPos(w-#Version.App-(w-#lines[1]),6)
  945.             term.write("v"..Version.App)
  946.  
  947.             sleep(1)
  948.             break
  949.         end
  950.     elseif ev[1]=="key" then
  951.         if ev[2]==keys.right or ev[2]==keys.pageDown then
  952.             index=index+1
  953.         elseif ev[2]==keys.left or ev[2]==keys.pageUp then
  954.             index=index-1
  955.         end
  956.     end
  957.     if index<1 then index=1
  958.     elseif index>#wins then index=#wins end
  959. end
  960.  
  961. if rerun then term.setTextColor(colors.white)shell.run"clear" return shell.run(shell.getRunningProgram(),unpack(Args)) end
Advertisement
Add Comment
Please, Sign In to add comment