nim-chroprof/tests/utils.nim

67 lines
1.9 KiB
Nim
Raw Permalink Normal View History

2024-02-29 17:55:45 -03:00
import chronos
2024-02-29 20:54:00 -03:00
import ../chroprof/[api, events, profiler]
2024-02-29 17:55:45 -03:00
2024-03-01 13:44:06 -03:00
type SimpleEvent* = object
procedure*: string
state*: ExtendedFutureState
2024-02-29 17:55:45 -03:00
# XXX this is sort of bad cause we get global state all over, but the fact we
# can't use closures on callbacks and that callbacks themselves are just
# global vars means we can't really do much better for now.
var recording*: seq[SimpleEvent]
var rawRecording*: seq[Event]
var fakeTime*: Moment = Moment.init(0, 1.milliseconds)
2024-02-29 17:55:45 -03:00
proc recordEvent(event: Event) {.nimcall, gcsafe, raises: [].} =
{.cast(gcsafe).}:
recording.add(
2024-03-01 13:44:06 -03:00
SimpleEvent(procedure: $event.location.procedure, state: event.newState)
)
2024-02-29 17:55:45 -03:00
var timeShifted = event
timeShifted.timestamp = fakeTime
rawRecording.add(timeShifted)
proc recordSegment*(segment: string) =
{.cast(gcsafe).}:
2024-03-01 13:44:06 -03:00
recording.add(SimpleEvent(procedure: segment, state: ExtendedFutureState.Running))
2024-02-29 17:55:45 -03:00
proc stopRecording*(): void =
2024-02-29 17:55:45 -03:00
recording = @[]
rawRecording = @[]
2024-03-01 14:22:19 -03:00
detachMonitoring()
2024-02-29 17:55:45 -03:00
proc startRecording*() =
stopRecording()
2024-03-01 14:22:19 -03:00
attachMonitoring(recordEvent)
2024-02-29 17:55:45 -03:00
proc forProc*(self: var MetricsTotals, procedure: string): AggregateMetrics =
for (key, aggMetrics) in self.mpairs:
if key.procedure == procedure:
return aggMetrics
proc resetTime*() =
fakeTime = Moment.now()
proc advanceTime*(duration: Duration) =
fakeTime += duration
2024-03-01 13:44:06 -03:00
proc advanceTimeAsync*(duration: Duration): Future[void] =
2024-02-29 17:55:45 -03:00
# Simulates a non-blocking operation that takes the provided duration to
# complete.
var retFuture = newFuture[void]("advanceTimeAsync")
var timer: TimerCallback
proc completion(data: pointer) {.gcsafe.} =
2024-03-01 13:44:06 -03:00
if not (retFuture.finished()):
2024-02-29 17:55:45 -03:00
advanceTime(duration)
retFuture.complete()
# The actual value for the timer is irrelevant, the important thing is that
# this causes the parent to pause before we advance time.
2024-03-01 13:44:06 -03:00
timer =
setTimer(Moment.fromNow(10.milliseconds), completion, cast[pointer](retFuture))
2024-02-29 17:55:45 -03:00
return retFuture