nimprof.nim 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Profiling support for Nim. This is an embedded profiler that requires
  10. ## ``--profiler:on``. You only need to import this module to get a profiling
  11. ## report at program exit.
  12. when not defined(profiler) and not defined(memProfiler):
  13. {.error: "Profiling support is turned off! Enable profiling by passing `--profiler:on --stackTrace:on` to the compiler (see the Nim Compiler User Guide for more options).".}
  14. when defined(nimHasUsed):
  15. {.used.}
  16. # We don't want to profile the profiling code ...
  17. {.push profiler: off.}
  18. import hashes, algorithm, strutils, tables, sets
  19. when not defined(memProfiler):
  20. include "system/timers"
  21. const
  22. withThreads = compileOption("threads")
  23. tickCountCorrection = 50_000
  24. when not declared(system.StackTrace):
  25. type StackTrace = object
  26. lines: array[0..20, cstring]
  27. files: array[0..20, cstring]
  28. proc `[]`*(st: StackTrace, i: int): cstring = st.lines[i]
  29. # We use a simple hash table of bounded size to keep track of the stack traces:
  30. type
  31. ProfileEntry = object
  32. total: int
  33. st: StackTrace
  34. ProfileData = array[0..64*1024-1, ptr ProfileEntry]
  35. proc `==`(a, b: StackTrace): bool =
  36. for i in 0 .. high(a.lines):
  37. if a[i] != b[i]: return false
  38. result = true
  39. # XXX extract this data structure; it is generally useful ;-)
  40. # However a chain length of over 3000 is suspicious...
  41. var
  42. profileData: ProfileData
  43. emptySlots = profileData.len * 3 div 2
  44. maxChainLen = 0
  45. totalCalls = 0
  46. when not defined(memProfiler):
  47. var interval: Nanos = 5_000_000 - tickCountCorrection # 5ms
  48. proc setSamplingFrequency*(intervalInUs: int) =
  49. ## set this to change the sampling frequency. Default value is 5ms.
  50. ## Set it to 0 to disable time based profiling; it uses an imprecise
  51. ## instruction count measure instead then.
  52. if intervalInUs <= 0: interval = 0
  53. else: interval = intervalInUs * 1000 - tickCountCorrection
  54. when withThreads:
  55. import locks
  56. var
  57. profilingLock: Lock
  58. initLock profilingLock
  59. proc hookAux(st: StackTrace, costs: int) =
  60. # this is quite performance sensitive!
  61. when withThreads: acquire profilingLock
  62. inc totalCalls
  63. var last = high(st.lines)
  64. while last > 0 and isNil(st[last]): dec last
  65. var h = hash(pointer(st[last])) and high(profileData)
  66. # we use probing for maxChainLen entries and replace the encountered entry
  67. # with the minimal 'total' value:
  68. if emptySlots == 0:
  69. var minIdx = h
  70. var probes = maxChainLen
  71. while probes >= 0:
  72. if profileData[h].st == st:
  73. # wow, same entry found:
  74. inc profileData[h].total, costs
  75. return
  76. if profileData[minIdx].total < profileData[h].total:
  77. minIdx = h
  78. h = ((5 * h) + 1) and high(profileData)
  79. dec probes
  80. profileData[minIdx].total = costs
  81. profileData[minIdx].st = st
  82. else:
  83. var chain = 0
  84. while true:
  85. if profileData[h] == nil:
  86. profileData[h] = cast[ptr ProfileEntry](
  87. allocShared0(sizeof(ProfileEntry)))
  88. profileData[h].total = costs
  89. profileData[h].st = st
  90. dec emptySlots
  91. break
  92. if profileData[h].st == st:
  93. # wow, same entry found:
  94. inc profileData[h].total, costs
  95. break
  96. h = ((5 * h) + 1) and high(profileData)
  97. inc chain
  98. maxChainLen = max(maxChainLen, chain)
  99. when withThreads: release profilingLock
  100. when defined(memProfiler):
  101. const
  102. SamplingInterval = 50_000
  103. var
  104. gTicker {.threadvar.}: int
  105. proc requestedHook(): bool {.nimcall, locks: 0.} =
  106. if gTicker == 0:
  107. gTicker = SamplingInterval
  108. result = true
  109. dec gTicker
  110. proc hook(st: StackTrace, size: int) {.nimcall, locks: 0.} =
  111. when defined(ignoreAllocationSize):
  112. hookAux(st, 1)
  113. else:
  114. hookAux(st, size)
  115. else:
  116. var
  117. t0 {.threadvar.}: Ticks
  118. gTicker: int # we use an additional counter to
  119. # avoid calling 'getTicks' too frequently
  120. proc requestedHook(): bool {.nimcall, locks: 0.} =
  121. if interval == 0: result = true
  122. elif gTicker == 0:
  123. gTicker = 500
  124. if getTicks() - t0 > interval:
  125. result = true
  126. else:
  127. dec gTicker
  128. proc hook(st: StackTrace) {.nimcall, locks: 0.} =
  129. #echo "profiling! ", interval
  130. if interval == 0:
  131. hookAux(st, 1)
  132. else:
  133. hookAux(st, 1)
  134. t0 = getTicks()
  135. proc getTotal(x: ptr ProfileEntry): int =
  136. result = if isNil(x): 0 else: x.total
  137. proc cmpEntries(a, b: ptr ProfileEntry): int =
  138. result = b.getTotal - a.getTotal
  139. proc `//`(a, b: int): string =
  140. result = format("$1/$2 = $3%", a, b, formatFloat(a / b * 100.0, ffDecimal, 2))
  141. proc writeProfile() {.noconv.} =
  142. system.profilingRequestedHook = nil
  143. when declared(system.StackTrace):
  144. system.profilerHook = nil
  145. const filename = "profile_results.txt"
  146. echo "writing " & filename & "..."
  147. var f: File
  148. if open(f, filename, fmWrite):
  149. sort(profileData, cmpEntries)
  150. writeLine(f, "total executions of each stack trace:")
  151. var entries = 0
  152. for i in 0..high(profileData):
  153. if profileData[i] != nil: inc entries
  154. var perProc = initCountTable[string]()
  155. for i in 0..entries-1:
  156. var dups = initSet[string]()
  157. for ii in 0..high(StackTrace.lines):
  158. let procname = profileData[i].st[ii]
  159. if isNil(procname): break
  160. let p = $procname
  161. if not containsOrIncl(dups, p):
  162. perProc.inc(p, profileData[i].total)
  163. var sum = 0
  164. # only write the first 100 entries:
  165. for i in 0..min(100, entries-1):
  166. if profileData[i].total > 1:
  167. inc sum, profileData[i].total
  168. writeLine(f, "Entry: ", i+1, "/", entries, " Calls: ",
  169. profileData[i].total // totalCalls, " [sum: ", sum, "; ",
  170. sum // totalCalls, "]")
  171. for ii in 0..high(StackTrace.lines):
  172. let procname = profileData[i].st[ii]
  173. let filename = profileData[i].st.files[ii]
  174. if isNil(procname): break
  175. writeLine(f, " ", $filename & ": " & $procname, " ",
  176. perProc[$procname] // totalCalls)
  177. close(f)
  178. echo "... done"
  179. else:
  180. echo "... failed"
  181. var
  182. disabled: int
  183. proc disableProfiling*() =
  184. when declared(system.StackTrace):
  185. atomicDec disabled
  186. system.profilingRequestedHook = nil
  187. proc enableProfiling*() =
  188. when declared(system.StackTrace):
  189. if atomicInc(disabled) >= 0:
  190. system.profilingRequestedHook = requestedHook
  191. when declared(system.StackTrace):
  192. system.profilingRequestedHook = requestedHook
  193. system.profilerHook = hook
  194. addQuitProc(writeProfile)
  195. {.pop.}