use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering::Relaxed};
use std::sync::{Mutex, Once};
use std::time::{Duration, Instant};
use crate::meta::MetaKind;
pub(crate) static TAG: AtomicU32 = AtomicU32::new(0);
pub(crate) static OP: AtomicU32 = AtomicU32::new(0);
static STOP: AtomicBool = AtomicBool::new(false);
static STARTED: Once = Once::new();
static COUNTS: Mutex<Option<HashMap<(u32, u32), u64>>> = Mutex::new(None);
#[allow(dead_code)]
pub(crate) const OTHER: u32 = 0;
pub(crate) const INTERP: u32 = 1;
pub(crate) const GET_PROP: u32 = 2;
pub(crate) const GC: u32 = 3;
pub(crate) const ALLOC: u32 = 4;
pub(crate) const CONSOLE: u32 = 5;
pub(crate) const CALL: u32 = 6;
pub(crate) const RETURN: u32 = 7;
pub(crate) const SET_PROP: u32 = 8;
pub(crate) const UNDO: u32 = 9;
pub(crate) const GC_ROOTS: u32 = 10;
pub(crate) const GC_MARK: u32 = 11;
pub(crate) const GC_SWEEP: u32 = 12;
pub(crate) const GC_WEAK: u32 = 13;
pub(crate) const BIF: u32 = 0x1_0000;
pub(crate) const NATIVE: u32 = 0x2_0000;
const NAMES: [&str; 14] = [
"(other)",
"interpreter",
"property lookup",
"garbage collection",
"object allocation",
"console formatting",
"function entry",
"function return",
"property assignment",
"undo",
"gc: roots",
"gc: mark",
"gc: sweep",
"gc: weak references and dictionaries",
];
pub(crate) struct Guard(u32);
impl Drop for Guard {
fn drop(&mut self) {
TAG.store(self.0, Relaxed);
}
}
#[inline]
pub(crate) fn scope(tag: u32) -> Guard {
STARTED.call_once(start);
Guard(TAG.swap(tag, Relaxed))
}
fn start() {
*COUNTS.lock().expect("counts") = Some(HashMap::new());
std::thread::spawn(|| {
let period = Duration::from_micros(20);
let mut next = Instant::now();
let mut local: HashMap<(u32, u32), u64> = HashMap::new();
let mut taken: u64 = 0;
let live = std::env::var_os("HEXICON_PROF_LIVE").is_some();
let mut last_live = Instant::now();
while !STOP.load(Relaxed) {
let now = Instant::now();
if now < next {
std::hint::spin_loop();
continue;
}
next = now + period;
let tag = TAG.load(Relaxed);
if live && now.duration_since(last_live) > Duration::from_millis(50) {
last_live = now;
eprintln!("live: {}", tag_name(tag));
}
let op = if tag == INTERP {
OP.load(Relaxed)
} else {
u32::MAX
};
*local.entry((tag, op)).or_default() += 1;
taken += 1;
if taken % 65536 == 0 {
let mut counts = COUNTS.lock().expect("counts");
let counts = counts.get_or_insert_with(HashMap::new);
for (key, n) in local.drain() {
*counts.entry(key).or_default() += n;
}
}
}
let mut counts = COUNTS.lock().expect("counts");
let counts = counts.get_or_insert_with(HashMap::new);
for (key, n) in local.drain() {
*counts.entry(key).or_default() += n;
}
});
}
fn tag_name(tag: u32) -> String {
if tag >= NATIVE {
let n = tag - NATIVE;
let kind = MetaKind::ALL
.get((n >> 8) as usize)
.map_or("?", |kind| kind.name());
format!("method {kind} #{}", n & 0xff)
} else if tag >= BIF {
let n = tag - BIF;
format!("built-in function set {} #{}", n >> 8, n & 0xff)
} else {
NAMES
.get(tag as usize)
.map_or_else(|| format!("tag {tag}"), |name| (*name).to_owned())
}
}
pub fn report() {
STOP.store(true, Relaxed);
std::thread::sleep(Duration::from_millis(20));
let counts = COUNTS.lock().expect("counts").take().unwrap_or_default();
let total: u64 = counts.values().sum();
if total == 0 {
return;
}
let mut by_tag: HashMap<u32, u64> = HashMap::new();
let mut by_op: HashMap<u32, u64> = HashMap::new();
for (&(tag, op), &n) in &counts {
*by_tag.entry(tag).or_default() += n;
if tag == INTERP {
*by_op.entry(op).or_default() += n;
}
}
let pct = |n: u64| 100.0 * n as f64 / total as f64;
eprintln!("profile: {total} samples");
let mut tags: Vec<_> = by_tag.into_iter().collect();
tags.sort_by_key(|entry| std::cmp::Reverse(entry.1));
for (tag, n) in tags.iter().take(40) {
eprintln!("{:6.2}% {}", pct(*n), tag_name(*tag));
}
eprintln!("interpreter by opcode:");
let mut ops: Vec<_> = by_op.into_iter().collect();
ops.sort_by_key(|entry| std::cmp::Reverse(entry.1));
for (op, n) in ops.iter().take(30) {
let name = hexicon_bytecode::Opcode::from_byte(*op as u8)
.map_or_else(|| format!("0x{op:02x}"), |op| format!("{op:?}"));
eprintln!("{:6.2}% {name}", pct(*n));
}
}