garbage.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. // Copyright 2013 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package debug
  5. import (
  6. "runtime"
  7. "sort"
  8. "time"
  9. )
  10. // GCStats collect information about recent garbage collections.
  11. type GCStats struct {
  12. LastGC time.Time // time of last collection
  13. NumGC int64 // number of garbage collections
  14. PauseTotal time.Duration // total pause for all collections
  15. Pause []time.Duration // pause history, most recent first
  16. PauseQuantiles []time.Duration
  17. }
  18. // Implemented in package runtime.
  19. func readGCStats(*[]time.Duration)
  20. func enableGC(bool) bool
  21. func setGCPercent(int) int
  22. func freeOSMemory()
  23. func setMaxStack(int) int
  24. func setMaxThreads(int) int
  25. // ReadGCStats reads statistics about garbage collection into stats.
  26. // The number of entries in the pause history is system-dependent;
  27. // stats.Pause slice will be reused if large enough, reallocated otherwise.
  28. // ReadGCStats may use the full capacity of the stats.Pause slice.
  29. // If stats.PauseQuantiles is non-empty, ReadGCStats fills it with quantiles
  30. // summarizing the distribution of pause time. For example, if
  31. // len(stats.PauseQuantiles) is 5, it will be filled with the minimum,
  32. // 25%, 50%, 75%, and maximum pause times.
  33. func ReadGCStats(stats *GCStats) {
  34. // Create a buffer with space for at least two copies of the
  35. // pause history tracked by the runtime. One will be returned
  36. // to the caller and the other will be used as a temporary buffer
  37. // for computing quantiles.
  38. const maxPause = len(((*runtime.MemStats)(nil)).PauseNs)
  39. if cap(stats.Pause) < 2*maxPause {
  40. stats.Pause = make([]time.Duration, 2*maxPause)
  41. }
  42. // readGCStats fills in the pause history (up to maxPause entries)
  43. // and then three more: Unix ns time of last GC, number of GC,
  44. // and total pause time in nanoseconds. Here we depend on the
  45. // fact that time.Duration's native unit is nanoseconds, so the
  46. // pauses and the total pause time do not need any conversion.
  47. readGCStats(&stats.Pause)
  48. n := len(stats.Pause) - 3
  49. stats.LastGC = time.Unix(0, int64(stats.Pause[n]))
  50. stats.NumGC = int64(stats.Pause[n+1])
  51. stats.PauseTotal = stats.Pause[n+2]
  52. stats.Pause = stats.Pause[:n]
  53. if len(stats.PauseQuantiles) > 0 {
  54. if n == 0 {
  55. for i := range stats.PauseQuantiles {
  56. stats.PauseQuantiles[i] = 0
  57. }
  58. } else {
  59. // There's room for a second copy of the data in stats.Pause.
  60. // See the allocation at the top of the function.
  61. sorted := stats.Pause[n : n+n]
  62. copy(sorted, stats.Pause)
  63. sort.Sort(byDuration(sorted))
  64. nq := len(stats.PauseQuantiles) - 1
  65. for i := 0; i < nq; i++ {
  66. stats.PauseQuantiles[i] = sorted[len(sorted)*i/nq]
  67. }
  68. stats.PauseQuantiles[nq] = sorted[len(sorted)-1]
  69. }
  70. }
  71. }
  72. type byDuration []time.Duration
  73. func (x byDuration) Len() int { return len(x) }
  74. func (x byDuration) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
  75. func (x byDuration) Less(i, j int) bool { return x[i] < x[j] }
  76. // SetGCPercent sets the garbage collection target percentage:
  77. // a collection is triggered when the ratio of freshly allocated data
  78. // to live data remaining after the previous collection reaches this percentage.
  79. // SetGCPercent returns the previous setting.
  80. // The initial setting is the value of the GOGC environment variable
  81. // at startup, or 100 if the variable is not set.
  82. // A negative percentage disables garbage collection.
  83. func SetGCPercent(percent int) int {
  84. old := setGCPercent(percent)
  85. runtime.GC()
  86. return old
  87. }
  88. // FreeOSMemory forces a garbage collection followed by an
  89. // attempt to return as much memory to the operating system
  90. // as possible. (Even if this is not called, the runtime gradually
  91. // returns memory to the operating system in a background task.)
  92. func FreeOSMemory() {
  93. freeOSMemory()
  94. }
  95. // SetMaxStack sets the maximum amount of memory that
  96. // can be used by a single goroutine stack.
  97. // If any goroutine exceeds this limit while growing its stack,
  98. // the program crashes.
  99. // SetMaxStack returns the previous setting.
  100. // The initial setting is 1 GB on 64-bit systems, 250 MB on 32-bit systems.
  101. //
  102. // SetMaxStack is useful mainly for limiting the damage done by
  103. // goroutines that enter an infinite recursion. It only limits future
  104. // stack growth.
  105. func SetMaxStack(bytes int) int {
  106. return setMaxStack(bytes)
  107. }
  108. // SetMaxThreads sets the maximum number of operating system
  109. // threads that the Go program can use. If it attempts to use more than
  110. // this many, the program crashes.
  111. // SetMaxThreads returns the previous setting.
  112. // The initial setting is 10,000 threads.
  113. //
  114. // The limit controls the number of operating system threads, not the number
  115. // of goroutines. A Go program creates a new thread only when a goroutine
  116. // is ready to run but all the existing threads are blocked in system calls, cgo calls,
  117. // or are locked to other goroutines due to use of runtime.LockOSThread.
  118. //
  119. // SetMaxThreads is useful mainly for limiting the damage done by
  120. // programs that create an unbounded number of threads. The idea is
  121. // to take down the program before it takes down the operating system.
  122. func SetMaxThreads(threads int) int {
  123. return setMaxThreads(threads)
  124. }
  125. // SetPanicOnFault controls the runtime's behavior when a program faults
  126. // at an unexpected (non-nil) address. Such faults are typically caused by
  127. // bugs such as runtime memory corruption, so the default response is to crash
  128. // the program. Programs working with memory-mapped files or unsafe
  129. // manipulation of memory may cause faults at non-nil addresses in less
  130. // dramatic situations; SetPanicOnFault allows such programs to request
  131. // that the runtime trigger only a panic, not a crash.
  132. // SetPanicOnFault applies only to the current goroutine.
  133. // It returns the previous setting.
  134. func SetPanicOnFault(enabled bool) bool
  135. // WriteHeapDump writes a description of the heap and the objects in
  136. // it to the given file descriptor.
  137. // The heap dump format is defined at http://golang.org/s/go13heapdump.
  138. func WriteHeapDump(fd uintptr)