Profiler API Reference

Runtime performance profiling with timing, memory tracking, and sampling support

Import

U std/profiler

Constants

NameValueDescription
PROFILER_DISABLED0Profiling disabled
PROFILER_ENABLED1Instrumentation mode enabled
PROFILER_SAMPLING2Sampling mode enabled
MAX_PROFILE_ENTRIES4096Maximum profile entries
SAMPLE_INTERVAL_MS10Default sampling interval

Structs

Timer

High-resolution timer for measuring code execution time.

Fields:

  • start_ns: i64 - Start time in nanoseconds
  • end_ns: i64 - End time in nanoseconds
  • running: i64 - 1 if timer is running
MethodSignatureDescription
newF new() -> TimerCreate new timer
startF start(&self) -> TimerStart the timer
stopF stop(&self) -> TimerStop the timer
elapsed_nsF elapsed_ns(&self) -> i64Get elapsed nanoseconds
elapsed_usF elapsed_us(&self) -> i64Get elapsed microseconds
elapsed_msF elapsed_ms(&self) -> i64Get elapsed milliseconds
resetF reset(&self) -> TimerReset timer to zero

ProfileEntry

Single profiling record for a named code region.

Fields:

  • name: str - Profile region name
  • call_count: i64 - Number of times called
  • total_time_ns: i64 - Total time spent
  • min_time_ns: i64 - Minimum time per call
  • max_time_ns: i64 - Maximum time per call
  • start_time: i64 - Start time (for nested timing)
  • depth: i64 - Call depth (for recursion tracking)
MethodSignatureDescription
newF new(name: str) -> ProfileEntryCreate profile entry
enterF enter(&self) -> i64Enter profiled region
exitF exit(&self) -> i64Exit profiled region
avg_time_nsF avg_time_ns(&self) -> i64Get average time per call
resetF reset(&self) -> i64Reset entry statistics

Profiler

Main profiling interface with instrumentation support.

Fields:

  • entries: i64 - Pointer to ProfileEntry array
  • entry_count: i64 - Number of entries
  • capacity: i64 - Array capacity
  • enabled: i64 - Profiler mode (DISABLED/ENABLED/SAMPLING)
  • start_time: i64 - Global start time
  • sample_interval: i64 - Sampling interval in ms
MethodSignatureDescription
newF new() -> ProfilerCreate profiler (default capacity 256)
enableF enable(&self) -> ProfilerEnable instrumentation mode
disableF disable(&self) -> ProfilerDisable profiling
enable_samplingF enable_sampling(&self, interval_ms: i64) -> ProfilerEnable sampling mode
is_enabledF is_enabled(&self) -> i64Check if profiling enabled
get_entryF get_entry(&self, name: str) -> i64Find or create entry
enterF enter(&self, name: str) -> i64Enter profiled region
exitF exit(&self, name: str) -> i64Exit profiled region
total_time_nsF total_time_ns(&self) -> i64Get total elapsed time
entry_countF entry_count(&self) -> i64Get number of entries
resetF reset(&self) -> i64Reset all entries
reportF report(&self) -> i64Print profiling report to stdout

MemoryProfiler

Track memory allocations and deallocations.

Fields:

  • allocations: i64 - Total allocations count
  • deallocations: i64 - Total deallocations count
  • bytes_allocated: i64 - Current allocated bytes
  • peak_bytes: i64 - Peak allocated bytes
  • total_allocated: i64 - Total bytes ever allocated
  • enabled: i64 - 1 if enabled
MethodSignatureDescription
newF new() -> MemoryProfilerCreate memory profiler
enableF enable(&self) -> MemoryProfilerEnable memory tracking
disableF disable(&self) -> MemoryProfilerDisable memory tracking
track_allocF track_alloc(&self, size: i64) -> i64Track allocation
track_deallocF track_dealloc(&self, size: i64) -> i64Track deallocation
current_bytesF current_bytes(&self) -> i64Get current allocated bytes
peak_bytesF peak_bytes(&self) -> i64Get peak allocated bytes
reportF report(&self) -> i64Print memory report
resetF reset(&self) -> i64Reset all counters

SampleProfiler

Statistical profiler that samples call stacks at intervals.

Fields:

  • samples: i64 - Pointer to sample buffer
  • sample_count: i64 - Number of samples collected
  • capacity: i64 - Buffer capacity
  • interval_ms: i64 - Sampling interval
  • running: i64 - 1 if sampling active
  • thread_handle: i64 - Sampler thread handle
MethodSignatureDescription
newF new(interval_ms: i64) -> SampleProfilerCreate sampling profiler
startF start(&self) -> i64Start sampling thread
stopF stop(&self) -> i64Stop sampling thread
record_sampleF record_sample(&self, func_ptr: i64) -> i64Record a sample
countF count(&self) -> i64Get sample count
analyzeF analyze(&self) -> i64Analyze and print results
resetF reset(&self) -> i64Clear all samples

FlameGraphBuilder

Generate flame graph data from stack samples.

Fields:

  • stack_samples: i64 - Array of stack samples
  • sample_count: i64 - Number of samples
  • capacity: i64 - Buffer capacity
MethodSignatureDescription
newF new() -> FlameGraphBuilderCreate flame graph builder
record_stackF record_stack(&self, stack_ptr: i64, depth: i64) -> i64Record stack sample
generate_foldedF generate_folded(&self, output_buffer: i64) -> i64Generate folded format

Global Functions

Profiler Management

FunctionSignatureDescription
profiler_initF profiler_init() -> i64Initialize global profiler
get_profilerF get_profiler() -> &ProfilerGet global profiler
mem_profiler_initF mem_profiler_init() -> i64Initialize memory profiler
get_mem_profilerF get_mem_profiler() -> &MemoryProfilerGet global memory profiler

Convenience Functions

FunctionSignatureDescription
profile_beginF profile_begin(name: str) -> i64Begin profiling region
profile_endF profile_end(name: str) -> i64End profiling region
profile_fnF profile_fn(name: str, fn_ptr: i64, arg: i64) -> i64Profile function call
timerF timer() -> TimerCreate timer
time_fnF time_fn(fn_ptr: i64, arg: i64) -> (i64, i64)Time function, return (result, elapsed_ns)

Usage

Basic Timing

U std/profiler

F main() -> i64 {
    t := timer()
    t.start()

    # ... code to measure ...
    do_work()

    t.stop()
    ms := t.elapsed_ms()
    us := t.elapsed_us()

    0
}

Instrumentation Profiling

U std/profiler

F main() -> i64 {
    p := get_profiler()
    p.enable()

    # Profile regions
    p.enter("region1")
    do_work()
    p.exit("region1")

    p.enter("region2")
    do_more_work()
    p.exit("region2")

    # Print report
    p.report()

    0
}

Convenience Functions

U std/profiler

F expensive_computation(n: i64) -> i64 {
    sum := 0
    i := 0
    L i < n {
        sum = sum + i
        i = i + 1
    }
    sum
}

F main() -> i64 {
    # Profile with begin/end
    profile_begin("compute")
    result := expensive_computation(1000000)
    profile_end("compute")

    # Or time a function call
    (result2, elapsed) := time_fn(expensive_computation_ptr, 1000000)

    get_profiler().report()

    0
}

Memory Profiling

U std/profiler

F main() -> i64 {
    mem := get_mem_profiler()
    mem.enable()

    # Allocations are tracked automatically
    buffer := malloc(1024)
    mem.track_alloc(1024)

    # Do work...

    free(buffer)
    mem.track_dealloc(1024)

    # Print report
    mem.report()

    0
}

Sampling Profiler

U std/profiler

F main() -> i64 {
    # Sample every 10ms
    sampler := SampleProfiler::new(10)
    sampler.start()

    # Run workload
    run_application()

    # Stop and analyze
    sampler.stop()
    sampler.analyze()

    0
}

Nested Profiling

U std/profiler

F outer() -> i64 {
    profile_begin("outer")

    inner()
    inner()

    profile_end("outer")
    0
}

F inner() -> i64 {
    profile_begin("inner")

    # Do work...
    compute()

    profile_end("inner")
    0
}

F main() -> i64 {
    get_profiler().enable()

    outer()

    get_profiler().report()

    0
}

Report Format

The report() method prints a table with the following columns:

  • Name: Profile region name
  • Calls: Number of times called
  • Total(ms): Total time spent in milliseconds
  • Avg(us): Average time per call in microseconds
  • Min(us): Minimum time in microseconds
  • Max(us): Maximum time in microseconds

Example output:

=== Profiling Report ===
Total time: 1543 ms

Name                          Calls      Total(ms)  Avg(us)   Min(us)   Max(us)
--------------------------------------------------------------------------------
compute                       1000000    1234       1         0         15
io_operation                  5000       309        61        50        150

Overview

The profiler module provides multiple profiling approaches:

  1. Timer: Manual high-resolution timing for specific code sections
  2. Profiler: Automatic instrumentation with enter/exit markers
  3. MemoryProfiler: Track allocations, deallocations, and memory usage
  4. SampleProfiler: Statistical profiling with periodic stack sampling
  5. FlameGraphBuilder: Generate flame graph visualization data

All profilers use nanosecond-resolution timing and support nested/recursive profiling. The global profiler instances allow easy integration without passing profiler objects through the call chain.