profile.rs 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. //! Where the process's time goes: `VICTORY_PROFILE=<from>,<to>,<ms>,<file>`
  2. //! samples the stacks of the busiest threads every `<ms>` milliseconds
  3. //! between two times (seconds, as `VICTORY_STACKS`), and writes them counted
  4. //! to `<file>` at the end (several of them, one after another, with `;`
  5. //! between). A thread that waits is sampled like one that
  6. //! runs: its top frame says which (`ntdll`'s system calls).
  7. //!
  8. //! The file: `thread <id> <start> <cpu ms> <samples> <name>`, then
  9. //! `stack <thread> <phase> <count> <frame>;<frame>;...` (innermost first, as
  10. //! `module+rva`), where the phase is what the caller's function says of the
  11. //! frame at that moment.
  12. use std::collections::HashMap;
  13. use std::io::Write;
  14. use std::time::{Duration, Instant};
  15. use windows_sys::Win32::Foundation::{CloseHandle, FILETIME, HANDLE};
  16. use windows_sys::Win32::System::Threading::{
  17. GetThreadTimes, OpenThread, THREAD_GET_CONTEXT, THREAD_QUERY_INFORMATION, THREAD_SUSPEND_RESUME,
  18. };
  19. use crate::crash::locate;
  20. use crate::stacks::{frames_of, name_of, other_threads, start_of};
  21. /// The threads sampled: those that ran most since they were last chosen.
  22. const BUSIEST: usize = 28;
  23. /// How often they are chosen anew.
  24. const CHOOSE: Duration = Duration::from_secs(1);
  25. /// What `VICTORY_PROFILE` says: from, to, every, the file.
  26. fn asked(list: &str) -> Option<(Duration, Duration, Duration, String)> {
  27. let mut parts = list.splitn(4, ',');
  28. let mut seconds = || parts.next()?.trim().parse::<f64>().ok();
  29. let (from, to, ms) = (seconds()?, seconds()?, seconds()?);
  30. let of = |s: f64| Duration::try_from_secs_f64(s).ok();
  31. let file = parts.next()?.trim().to_string();
  32. Some((of(from)?, of(to)?, of(ms / 1000.0)?, file)).filter(|(a, b, ms, f)| a < b && !ms.is_zero() && !f.is_empty())
  33. }
  34. struct Thread {
  35. handle: HANDLE,
  36. start: String,
  37. name: String,
  38. /// Its processor time, 100 ns: at first, when last chosen, now.
  39. first: u64,
  40. last: u64,
  41. now: u64,
  42. samples: u64,
  43. }
  44. fn cpu(thread: HANDLE) -> u64 {
  45. // SAFETY: zeroed is a valid FILETIME, and the calls write them.
  46. let mut t: [FILETIME; 4] = unsafe { std::mem::zeroed() };
  47. let [a, b, c, d] = &mut t;
  48. // SAFETY: an open thread; the pointers are to the structures above.
  49. unsafe { GetThreadTimes(thread, a, b, c, d) };
  50. let of = |f: &FILETIME| u64::from(f.dwHighDateTime) << 32 | u64::from(f.dwLowDateTime);
  51. of(&t[2]) + of(&t[3])
  52. }
  53. /// Reads `VICTORY_PROFILE` and, if set, starts the thread that samples.
  54. /// `phase` is asked at each round.
  55. pub fn profile_on_schedule(phase: fn() -> u32) {
  56. let Ok(list) = std::env::var("VICTORY_PROFILE") else {
  57. return;
  58. };
  59. let start = Instant::now();
  60. let all: Vec<_> = list.split(';').filter_map(asked).collect();
  61. std::thread::spawn(move || {
  62. for one in all {
  63. profile(one, start, phase);
  64. }
  65. });
  66. }
  67. fn profile((from, to, every, file): (Duration, Duration, Duration, String), start: Instant, phase: fn() -> u32) {
  68. std::thread::sleep(from.saturating_sub(start.elapsed()));
  69. eprintln!("VIctory: the profile begins");
  70. let mut threads: HashMap<u32, Thread> = HashMap::new();
  71. let mut chosen: Vec<u32> = Vec::new();
  72. let mut counts: HashMap<(u32, u32, Vec<u64>), u64> = HashMap::new();
  73. let mut phases: HashMap<u32, u64> = HashMap::new();
  74. let mut choose_at = Instant::now();
  75. let mut rounds = 0u64;
  76. while start.elapsed() < to {
  77. let round = Instant::now();
  78. if round >= choose_at {
  79. choose_at = round + CHOOSE;
  80. choose(&mut threads, &mut chosen);
  81. }
  82. let phase = phase();
  83. *phases.entry(phase).or_default() += 1;
  84. for id in &chosen {
  85. if let Some(t) = threads.get_mut(id) {
  86. let (frames, _) = frames_of(t.handle);
  87. t.samples += 1;
  88. if !frames.is_empty() {
  89. *counts.entry((*id, phase, frames)).or_default() += 1;
  90. }
  91. }
  92. }
  93. rounds += 1;
  94. std::thread::sleep(every.saturating_sub(round.elapsed()));
  95. }
  96. choose(&mut threads, &mut chosen);
  97. if let Err(e) = write(&file, &threads, &counts, &phases, rounds) {
  98. eprintln!("VIctory: the profile was not written: {e}");
  99. } else {
  100. eprintln!("VIctory: the profile is in {file}");
  101. }
  102. }
  103. /// Opens the threads that are new, and chooses the ones to sample.
  104. fn choose(threads: &mut HashMap<u32, Thread>, chosen: &mut Vec<u32>) {
  105. for id in other_threads() {
  106. threads.entry(id).or_insert_with(|| {
  107. // SAFETY: opens a thread of our own process; kept open for the
  108. // profile's life, so the id stays its own.
  109. let handle =
  110. unsafe { OpenThread(THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION, 0, id) };
  111. let first = if handle.is_null() { 0 } else { cpu(handle) };
  112. Thread {
  113. handle,
  114. start: if handle.is_null() { String::new() } else { locate(start_of(handle)) },
  115. name: if handle.is_null() { String::new() } else { name_of(handle) },
  116. first,
  117. last: first,
  118. now: first,
  119. samples: 0,
  120. }
  121. });
  122. }
  123. let mut ran: Vec<(u64, u32)> = Vec::new();
  124. for (&id, t) in threads.iter_mut().filter(|(_, t)| !t.handle.is_null()) {
  125. t.now = cpu(t.handle);
  126. ran.push((t.now - t.last, id));
  127. t.last = t.now;
  128. }
  129. ran.sort_unstable_by(|a, b| b.cmp(a));
  130. *chosen = ran.into_iter().take(BUSIEST).map(|(_, id)| id).collect();
  131. }
  132. fn write(
  133. file: &str,
  134. threads: &HashMap<u32, Thread>,
  135. counts: &HashMap<(u32, u32, Vec<u64>), u64>,
  136. phases: &HashMap<u32, u64>,
  137. rounds: u64,
  138. ) -> std::io::Result<()> {
  139. let mut out = std::io::BufWriter::new(std::fs::File::create(file)?);
  140. writeln!(out, "rounds {rounds}")?;
  141. for (phase, n) in phases {
  142. writeln!(out, "phase {phase} {n}")?;
  143. }
  144. let mut names: HashMap<u64, String> = HashMap::new();
  145. for (id, t) in threads {
  146. writeln!(out, "thread {id} {} {} {} {}", t.start, (t.now - t.first) / 10_000, t.samples, t.name)?;
  147. if !t.handle.is_null() {
  148. // SAFETY: opened by `choose`.
  149. unsafe { CloseHandle(t.handle) };
  150. }
  151. }
  152. for ((id, phase, frames), n) in counts {
  153. write!(out, "stack {id} {phase} {n} ")?;
  154. for f in frames {
  155. let name = names.entry(*f).or_insert_with(|| locate(*f as usize));
  156. write!(out, "{name};")?;
  157. }
  158. writeln!(out)?;
  159. }
  160. out.flush()
  161. }
  162. #[cfg(test)]
  163. mod tests {
  164. use super::*;
  165. #[test]
  166. fn what_is_asked_is_read_whole_or_not_at_all() {
  167. assert_eq!(
  168. asked("150, 160.5,5,D:\\a b,c.txt"),
  169. Some((
  170. Duration::from_secs(150),
  171. Duration::from_millis(160_500),
  172. Duration::from_millis(5),
  173. "D:\\a b,c.txt".to_string()
  174. ))
  175. );
  176. assert_eq!(asked("150,160,5"), None);
  177. assert_eq!(asked("160,150,5,x"), None);
  178. assert_eq!(asked("a,160,5,x"), None);
  179. assert_eq!(asked("-1,160,5,x"), None);
  180. assert_eq!(asked("1,160,0,x"), None);
  181. }
  182. }