colrowmajor.lua 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. --Stephen Stengel
  2. --A program that shows the effect of caching.
  3. --Doing operations with large matricies can cause many cache misses. By
  4. --selecting a small square of a matrix, you can load all its data into
  5. --cache. This reduces the number of cache misses.
  6. --Todo: make a flat matrix version of the functions. This should increase speed by another magnitude.
  7. function main()
  8. math.randomseed( os.time() )
  9. local squareSize = tonumber(arg[1]) or 10 --if no input, default 10
  10. local iterations = tonumber(arg[2]) or 1000 --if no input, default 1000
  11. io.write( string.format("squareSize: %d\n", squareSize) )
  12. io.write( string.format("iterations: %d\n", iterations) )
  13. --Start tests
  14. fwrite("Timing Row-Major...")
  15. timeMakeRandom(iterations, squareSize, createRandMatRowMaj)
  16. fwrite("Timing Column-Major...")
  17. timeMakeRandom(iterations, squareSize, createRandMatColMaj)
  18. end
  19. function timeMakeRandom(iterations, squareSize, createFunction)
  20. local lowtime = math.huge
  21. for i = 1, 5 do
  22. local start = os.clock()
  23. local anArray = createZeroArray(squareSize)
  24. for j = 1, iterations do
  25. createFunction(anArray)
  26. end
  27. local total = os.clock() - start
  28. if total < lowtime then
  29. lowtime = total
  30. end
  31. end
  32. --~ fwrite(" done!\tLowest time of five trials: %.2f seconds!\n", lowtime)
  33. fwrite(" done!\tLowest time of five trials: %f seconds!\n", lowtime)
  34. return total
  35. end
  36. function printMatrix(myMat)
  37. for i = 1, #myMat do
  38. for j = 1, #myMat[i] do
  39. fwrite("%d ", myMat[i][j])
  40. end
  41. fwrite("\n")
  42. end
  43. end
  44. function createZeroArray(len)
  45. local outArray = {}
  46. for i = 1, len do
  47. outArray[i] = {}
  48. for j = 1, len do
  49. outArray[i][j] = 0
  50. end
  51. end
  52. return outArray
  53. end
  54. function createRandMatColMaj(myArray)
  55. local len = #myArray
  56. for i = 1, len do
  57. for j = 1, len do
  58. myArray[j][i] = math.random(100)
  59. end
  60. end
  61. end
  62. function createRandMatRowMaj(myArray)
  63. local len = #myArray
  64. for i = 1, len do
  65. for j = 1, len do
  66. myArray[i][j] = math.random(100)
  67. end
  68. end
  69. end
  70. --function similar to C printf
  71. function fwrite(fmt, ...)
  72. return io.write( string.format(fmt, ...) )
  73. end
  74. --------
  75. main()--
  76. --------