Skip to content

Instantly share code, notes, and snippets.

@OverShifted
Last active January 18, 2022 14:42
Show Gist options
  • Save OverShifted/5e2829a85d40cf5bc531e7a2505ca970 to your computer and use it in GitHub Desktop.
Save OverShifted/5e2829a85d40cf5bc531e7a2505ca970 to your computer and use it in GitHub Desktop.
Basic instrumentation profiler for Rust
// Based on https://gist.github.com/TheCherno/31f135eea6ee729ab5f26a6908eb3a5e
// Usage:
// 1. Call init before doing anything else with this file/snippet.
// 2. Put `let _timer = Timer::new()` at the begining of any scope you want to measure (DO NOT name the variable `_`. Because it will be dropped instantly after creation.)
// 3. Drag result.json into chrome://tracing (If you have a chromium-based browser) or https://ui.perfetto.dev for visualization
static mut TIMER: Option<std::time::Instant> = None;
static mut OUT_STREAM: String = String::new();
static mut NOT_FIRST: bool = false;
pub struct Timer {
name: &'static str,
start: std::time::Duration
}
impl Timer {
pub fn new(name: &'static str) -> Timer {
Timer {
name,
start: unsafe { TIMER.unwrap().elapsed() }
}
}
}
impl Drop for Timer {
fn drop(&mut self) {
unsafe {
// OUT_STREAM.push_str("{");
// OUT_STREAM.push_str("\"cat\":\"function\",");
// OUT_STREAM.push_str(&format!("\"dur\":{},", (TIMER.unwrap().elapsed() - self.start).as_micros()));
// OUT_STREAM.push_str(&format!("\"name\":\"{}\",", self.name));
// OUT_STREAM.push_str("\"ph\":\"X\",");
// OUT_STREAM.push_str("\"pid\":0,");
// OUT_STREAM.push_str("\"tid\":0,");
// OUT_STREAM.push_str(&format!("\"ts\":{}", self.start.as_micros()));
// OUT_STREAM.push_str("}");
if NOT_FIRST {
OUT_STREAM.push_str(",");
}
NOT_FIRST = true;
OUT_STREAM.push_str(&format!("{{\"cat\":\"function\",\"dur\":{},\"name\":\"{}\",\"ph\":\"X\",\"pid\":0,\"tid\":0,\"ts\":{}}}", (TIMER.unwrap().elapsed() - self.start).as_micros(), self.name, self.start.as_micros()));
}
}
}
pub fn init() {
unsafe {
TIMER = Some(std::time::Instant::now());
OUT_STREAM = "{\"otherData\": {},\"traceEvents\":[".to_string();
}
}
pub fn shutdown() {
unsafe {
OUT_STREAM.push_str("]}");
std::fs::write("result.json", OUT_STREAM.as_str()).unwrap();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment