summaryrefslogtreecommitdiff
path: root/src/yourkit/scala/tools/util/YourkitProfiling.scala
blob: 677a85112b0daf876296fdc1136a16b4e9b111c5 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package scala.tools
package util

import com.yourkit.api._
import com.yourkit.runtime._
import nsc.io._

class YourkitProfiling extends Profiling {
  @volatile private var active = false
  @volatile private var freq: Option[Int] = None
  lazy val controller = new Controller

  def defaultFreq = 100
  def allocationFreq = freq
  def setAllocationFreq(x: Int) = freq = if (x <= 0) None else Some(x)

  def startRecordingAllocations() = {
    controller.startAllocationRecording(true, freq getOrElse defaultFreq, false, 0)
  }
  def stopRecordingAllocations() = {
    controller.stopAllocationRecording()
  }

  def startProfiling(): Unit = {
    if (isActive)
      return

    active = true
    daemonize {
      try {
        controller.startCPUProfiling(ProfilingModes.CPU_SAMPLING, Controller.DEFAULT_FILTERS)
        if (freq.isDefined)
          startRecordingAllocations()
      }
      catch {
        case _: PresentableException  => () // if it's already running, no big deal
      }
    }
  }

  def captureSnapshot() = {
    daemonize(controller.captureSnapshot(ProfilingModes.SNAPSHOT_WITH_HEAP))
  }

  def stopProfiling() = {
    try {
      if (freq.isDefined)
        stopRecordingAllocations()

      controller.stopCPUProfiling()
    }
    catch {
      case _: PresentableException  => () // if it's already running, no big deal
    }
    finally active = false
  }

  def advanceGeneration(desc: String) {
    controller.advanceGeneration(desc)
  }

  def isActive = active
}