nimprof.nim 6.6 KB

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