nimprof.nim 6.6 KB

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