1use anyhow::{Context, Result, bail};
21use std::collections::BTreeMap;
22use std::path::{Path, PathBuf};
23
24pub const EXTENSION: &str = ".cachegrind.out";
28
29#[derive(Debug, Clone, Default, PartialEq)]
36pub struct Origin {
37 pub runner: String,
42 pub commit: Option<String>,
46 pub bench: String,
47 pub subject: String,
48}
49
50pub fn path_for(dir: &Path, bench: &str, subject: &str) -> Result<PathBuf> {
64 for (what, name) in [("benchmark", bench), ("subject", subject)] {
65 crate::record::check_name(what, name)?;
66 let plain = !name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\']);
67 if !plain {
68 bail!(
69 "--profile-dir cannot name a file after {what} {name:?}: it is not a plain file name"
70 );
71 }
72 }
73 Ok(dir.join(bench).join(format!("{subject}{EXTENSION}")))
74}
75
76pub fn write(dest: &Path, raw: &[u8], origin: &Origin) -> Result<()> {
82 let parent = dest.parent().context("a profile path has a directory")?;
83 std::fs::create_dir_all(parent)
84 .with_context(|| format!("could not create {}", parent.display()))?;
85 let mut tmp = tempfile::NamedTempFile::new_in(parent)
86 .with_context(|| format!("could not write a profile in {}", parent.display()))?;
87 let mut head = String::new();
91 let fields = [
92 ("runner", Some(origin.runner.as_str())),
93 ("commit", origin.commit.as_deref()),
94 ("bench", Some(origin.bench.as_str())),
95 ("subject", Some(origin.subject.as_str())),
96 ];
97 for (key, value) in fields {
98 if let Some(v) = value {
99 let v: String = v
100 .chars()
101 .map(|c| if c.is_control() { ' ' } else { c })
102 .collect();
103 head.push_str(&format!("desc: tak {key}: {v}\n"));
104 }
105 }
106 use std::io::Write;
107 tmp.write_all(head.as_bytes())
108 .and_then(|()| tmp.write_all(raw))
109 .with_context(|| format!("could not write {}", dest.display()))?;
110 tmp.persist(dest)
111 .with_context(|| format!("could not write {}", dest.display()))?;
112 Ok(())
113}
114
115#[derive(Debug, Clone, Default, PartialEq)]
117pub struct Function {
118 pub ir: u64,
120 pub files: BTreeMap<String, u64>,
124}
125
126impl Function {
127 pub fn file(&self) -> &str {
130 self.files
131 .iter()
132 .max_by(|a, b| a.1.cmp(b.1).then_with(|| b.0.cmp(a.0)))
133 .map_or("???", |(f, _)| f.as_str())
134 }
135}
136
137#[derive(Debug, Clone, Default, PartialEq)]
139pub struct Profile {
140 pub desc: Vec<String>,
142 pub cmd: Option<String>,
144 pub total: u64,
146 pub functions: BTreeMap<String, Function>,
151}
152
153impl Profile {
154 pub fn origin(&self) -> Option<Origin> {
157 let get = |key: &str| {
158 self.desc.iter().find_map(|d| {
159 d.strip_prefix("tak ")?
160 .strip_prefix(key)?
161 .strip_prefix(": ")
162 .map(str::to_string)
163 })
164 };
165 Some(Origin {
166 runner: get("runner")?,
167 commit: get("commit"),
168 bench: get("bench").unwrap_or_default(),
169 subject: get("subject").unwrap_or_default(),
170 })
171 }
172
173 pub fn runner(&self) -> Option<String> {
175 self.origin().map(|o| o.runner)
176 }
177
178 pub fn load(path: &Path) -> Result<Profile> {
179 let text = std::fs::read_to_string(path)
180 .with_context(|| format!("could not read {}", path.display()))?;
181 parse(&text).with_context(|| format!("could not parse {}", path.display()))
182 }
183}
184
185#[derive(Default)]
189struct Names {
190 files: BTreeMap<String, String>,
191 fns: BTreeMap<String, String>,
192}
193
194fn resolve(table: &mut BTreeMap<String, String>, value: &str) -> Result<String> {
200 let value = value.trim();
201 let Some(rest) = value.strip_prefix('(') else {
202 return Ok(value.to_string());
203 };
204 let Some((id, name)) = rest.split_once(')') else {
205 return Ok(value.to_string());
207 };
208 if !id.chars().all(|c| c.is_ascii_digit()) || id.is_empty() {
209 return Ok(value.to_string());
210 }
211 let name = name.trim();
212 if name.is_empty() {
213 return table
214 .get(id)
215 .cloned()
216 .with_context(|| format!("name ({id}) is used before it is defined"));
217 }
218 table.insert(id.to_string(), name.to_string());
219 Ok(name.to_string())
220}
221
222pub fn parse(text: &str) -> Result<Profile> {
232 let mut p = Profile::default();
233 let mut names = Names::default();
234 let mut ir_col: Option<usize> = None;
237 let mut positions = 1usize;
238 let mut summary: Option<u64> = None;
239 let mut file = String::from("???");
240 let mut func = String::from("???");
241 let mut skip_cost = false;
244 let mut sum = 0u64;
245
246 for (i, line) in text.lines().enumerate() {
247 let n = i + 1;
248 let line = line.trim();
252 if line.is_empty() || line.starts_with('#') {
253 continue;
254 }
255 let first = line.as_bytes()[0];
256 if first.is_ascii_digit() || matches!(first, b'+' | b'-' | b'*') {
257 if skip_cost {
258 skip_cost = false;
259 continue;
260 }
261 let col =
262 ir_col.with_context(|| format!("line {n}: a cost before the `events:` line"))?;
263 let fields: Vec<&str> = line.split_whitespace().collect();
264 if fields.len() < positions {
265 bail!("line {n}: expected {positions} position column(s): {line}");
266 }
267 let ir = match fields.get(positions + col) {
269 Some(v) => v
270 .parse::<u64>()
271 .with_context(|| format!("line {n}: not a count: {v}"))?,
272 None => 0,
273 };
274 let f = p.functions.entry(func.clone()).or_default();
275 f.ir += ir;
276 *f.files.entry(file.clone()).or_default() += ir;
277 sum += ir;
278 continue;
279 }
280 if let Some(rest) = line.strip_prefix("desc:") {
281 p.desc.push(rest.trim().to_string());
282 } else if let Some(rest) = line.strip_prefix("cmd:") {
283 p.cmd = Some(rest.trim().to_string());
284 } else if let Some(rest) = line.strip_prefix("events:") {
285 let events: Vec<&str> = rest.split_whitespace().collect();
286 ir_col = Some(
287 events
288 .iter()
289 .position(|e| *e == "Ir")
290 .with_context(|| format!("line {n}: no `Ir` event in `{line}`"))?,
291 );
292 } else if let Some(rest) = line.strip_prefix("positions:") {
293 positions = rest.split_whitespace().count().max(1);
294 } else if let Some(rest) = line
295 .strip_prefix("summary:")
296 .or_else(|| line.strip_prefix("totals:"))
297 {
298 let col = ir_col.with_context(|| format!("line {n}: a total before `events:`"))?;
299 if let Some(v) = rest.split_whitespace().nth(col) {
300 summary = Some(
301 v.parse()
302 .with_context(|| format!("line {n}: not a count: {v}"))?,
303 );
304 }
305 } else if let Some((key, value)) = line.split_once('=') {
306 match key {
307 "fl" | "fi" | "fe" => file = resolve(&mut names.files, value)?,
310 "fn" => func = resolve(&mut names.fns, value)?,
311 "cfl" | "cfi" => {
314 resolve(&mut names.files, value)?;
315 }
316 "cfn" => {
317 resolve(&mut names.fns, value)?;
318 }
319 "calls" => skip_cost = true,
320 _ => {}
321 }
322 }
323 }
326 if ir_col.is_none() {
327 bail!("not a cachegrind profile: no `events:` line");
328 }
329 p.total = summary.unwrap_or(sum);
330 Ok(p)
331}
332
333#[derive(Debug, Clone, PartialEq)]
335pub struct Delta {
336 pub name: String,
337 pub file: String,
339 pub base: u64,
340 pub head: u64,
341}
342
343impl Delta {
344 pub fn change(&self) -> i128 {
345 self.head as i128 - self.base as i128
346 }
347}
348
349pub fn diff(base: &Profile, head: &Profile) -> Vec<Delta> {
356 let empty = Function::default();
357 let mut out: Vec<Delta> = base
358 .functions
359 .keys()
360 .chain(head.functions.keys())
361 .collect::<std::collections::BTreeSet<_>>()
362 .into_iter()
363 .filter_map(|name| {
364 let b = base.functions.get(name).unwrap_or(&empty);
365 let h = head.functions.get(name).unwrap_or(&empty);
366 (b.ir != h.ir).then(|| Delta {
367 name: name.clone(),
368 file: if h.files.is_empty() { b } else { h }.file().to_string(),
369 base: b.ir,
370 head: h.ir,
371 })
372 })
373 .collect();
374 out.sort_by(|a, b| {
376 b.change()
377 .unsigned_abs()
378 .cmp(&a.change().unsigned_abs())
379 .then_with(|| a.name.cmp(&b.name))
380 });
381 out
382}
383
384#[derive(Debug, Clone)]
386pub struct Pair {
387 pub label: String,
389 pub base: Profile,
390 pub head: Profile,
391}
392
393#[derive(Debug, Clone, Default, PartialEq)]
395pub struct Unpaired {
396 pub base: Vec<String>,
397 pub head: Vec<String>,
398}
399
400fn scan(dir: &Path) -> Result<BTreeMap<String, PathBuf>> {
402 let mut out = BTreeMap::new();
403 let benches =
404 std::fs::read_dir(dir).with_context(|| format!("could not read {}", dir.display()))?;
405 for bench in benches {
406 let bench = bench?;
407 if !bench.file_type()?.is_dir() {
408 continue;
409 }
410 for file in std::fs::read_dir(bench.path())? {
411 let file = file?;
412 let name = file.file_name().to_string_lossy().to_string();
413 if file.file_type()?.is_file() && name.ends_with(EXTENSION) {
414 out.insert(
415 format!("{}/{name}", bench.file_name().to_string_lossy()),
416 file.path(),
417 );
418 }
419 }
420 }
421 Ok(out)
422}
423
424fn label(rel: &str) -> String {
432 let (bench, file) = rel.split_once('/').unwrap_or(("", rel));
433 let subject = file.strip_suffix(EXTENSION).unwrap_or(file);
434 match bench {
435 "" => text(subject),
436 _ if subject == crate::config::SELF_TOOL => text(bench),
437 _ => format!("{} ({})", text(bench), text(subject)),
438 }
439}
440
441fn text(s: &str) -> String {
448 let s = crate::compare::escape_control(s);
449 let mut out = String::with_capacity(s.len());
450 for c in s.chars() {
451 if "\\`*_[]<>#|!~&".contains(c) {
452 out.push('\\');
453 }
454 out.push(c);
455 }
456 out
457}
458
459pub fn load(base: &Path, head: &Path) -> Result<(Vec<Pair>, Unpaired)> {
462 for p in [base, head] {
463 if !p.exists() {
464 bail!("{} does not exist", p.display());
465 }
466 }
467 match (base.is_dir(), head.is_dir()) {
468 (false, false) => {
469 let name = head
470 .file_name()
471 .map(|n| n.to_string_lossy().to_string())
472 .unwrap_or_default();
473 let pair = Pair {
474 label: label(&name),
475 base: Profile::load(base)?,
476 head: Profile::load(head)?,
477 };
478 Ok((vec![pair], Unpaired::default()))
479 }
480 (true, true) => {
481 let (b, h) = (scan(base)?, scan(head)?);
482 let mut pairs = Vec::new();
483 let mut unpaired = Unpaired::default();
484 for (rel, path) in &h {
485 match b.get(rel) {
486 Some(bpath) => pairs.push(Pair {
487 label: label(rel),
488 base: Profile::load(bpath)?,
489 head: Profile::load(path)?,
490 }),
491 None => unpaired.head.push(rel.clone()),
492 }
493 }
494 unpaired.base = b.keys().filter(|k| !h.contains_key(*k)).cloned().collect();
495 Ok((pairs, unpaired))
496 }
497 _ => bail!(
498 "compare a directory with a directory, or a profile with a profile: {} and {}",
499 base.display(),
500 head.display()
501 ),
502 }
503}
504
505fn cell(name: &str) -> String {
513 crate::compare::code_cell(&crate::compare::code(name))
514}
515
516fn mismatch(side: &str, p: &Profile, recorded: &dyn Fn(&Origin) -> Option<u64>) -> String {
524 let Some(origin) = p.origin() else {
525 return String::new();
526 };
527 match (origin.commit.as_deref(), recorded(&origin)) {
528 (Some(commit), Some(n)) if n != p.total => format!(
529 "\n> [!WARNING]\n> The {side} profile totals {} instructions, but the lowest count \
530 recorded for {} in git notes is {}. The profile is not from the run that count \
531 came from.\n",
532 crate::compare::thousands(p.total as f64),
533 cell(&commit[..commit.len().min(12)]),
534 crate::compare::thousands(n as f64),
535 ),
536 _ => String::new(),
537 }
538}
539
540fn signed(v: i128) -> String {
541 let n = crate::compare::thousands(v.unsigned_abs() as f64);
542 match v.signum() {
543 1 => format!("+{n}"),
544 -1 => format!("-{n}"),
545 _ => n,
546 }
547}
548
549pub fn markdown(
559 pairs: &[Pair],
560 unpaired: &Unpaired,
561 top: usize,
562 recorded: &dyn Fn(&Origin) -> Option<u64>,
563) -> String {
564 let mut out = String::from("## Where the instructions went\n");
565 if pairs.is_empty() {
566 out.push_str("\nNo benchmark has a profile on both sides, so nothing was explained.\n");
567 }
568 for pair in pairs {
569 let (base, head) = (pair.base.total, pair.head.total);
570 let change = head as i128 - base as i128;
571 let pct = if base == 0 {
572 String::new()
573 } else {
574 format!(
575 ", **{}{:.2}%**",
576 if change >= 0 { "+" } else { "" },
577 change as f64 / base as f64 * 100.0
578 )
579 };
580 out.push_str(&format!(
581 "\n### {}\n\n{} → {} instructions ({}{pct}).\n",
582 pair.label,
583 crate::compare::thousands(base as f64),
584 crate::compare::thousands(head as f64),
585 signed(change),
586 ));
587 if let (Some(b), Some(h)) = (pair.base.runner(), pair.head.runner())
588 && b != h
589 {
590 out.push_str(&format!(
591 "\n> [!WARNING]\n> Profiled on different runner classes ({} and {}). \
592 Library code differs between machines, so some of what follows is the \
593 machine rather than the change.\n",
594 cell(&b),
595 cell(&h)
596 ));
597 }
598 out.push_str(&mismatch("base", &pair.base, recorded));
599 out.push_str(&mismatch("head", &pair.head, recorded));
600 let deltas = diff(&pair.base, &pair.head);
601 if deltas.is_empty() {
602 out.push_str("\nNo function's instruction count changed.\n");
603 continue;
604 }
605 let shown = deltas.len().min(top);
606 if shown < deltas.len() {
607 out.push_str(&format!(
608 "\n{} function(s) changed; the {shown} largest:\n\n",
609 deltas.len()
610 ));
611 } else {
612 out.push_str(&format!("\n{} function(s) changed:\n\n", deltas.len()));
613 }
614 out.push_str("| function | Δ | base | head | file |\n|---|---:|---:|---:|---|\n");
615 for d in &deltas[..shown] {
616 out.push_str(&format!(
617 "| {} | **{}** | {} | {} | {} |\n",
618 cell(&d.name),
619 signed(d.change()),
620 crate::compare::thousands(d.base as f64),
621 crate::compare::thousands(d.head as f64),
622 cell(&d.file),
623 ));
624 }
625 let rest = &deltas[shown..];
626 if !rest.is_empty() {
627 let sum: i128 = rest.iter().map(Delta::change).sum();
628 out.push_str(&format!(
629 "| {} more | {} | | | |\n",
630 rest.len(),
631 signed(sum)
632 ));
633 }
634 }
635 for (side, list) in [("base", &unpaired.base), ("head", &unpaired.head)] {
636 if !list.is_empty() {
637 out.push_str(&format!(
638 "\nOnly in the {side}, so not explained: {}\n",
639 list.iter().map(|p| cell(p)).collect::<Vec<_>>().join(", ")
640 ));
641 }
642 }
643 out.push_str(
644 "\n<sub>Self cost per function: code inlined into a function counts as its own. \
645 Only the benchmarked process is profiled, not programs it starts. \
646 `???` is code without symbols.</sub>\n",
647 );
648 out
649}
650
651#[cfg(test)]
652mod tests {
653 use super::*;
654
655 const BASE: &str = include_str!("../tests/fixtures/profile/base.cachegrind.out");
656 const HEAD: &str = include_str!("../tests/fixtures/profile/head.cachegrind.out");
657
658 #[test]
659 fn a_profile_sums_each_function_across_its_files() {
660 let p = parse(BASE).unwrap();
661 assert_eq!(p.cmd.as_deref(), Some("./mycli --help"));
662 assert_eq!(p.total, 1_500);
663 let f = &p.functions["mycli::parse_args"];
665 assert_eq!(f.ir, 600);
666 assert_eq!(f.files["src/args.rs"], 500);
667 assert_eq!(f.files["src/util.rs"], 100);
668 assert_eq!(f.file(), "src/args.rs");
669 assert_eq!(p.functions.values().map(|f| f.ir).sum::<u64>(), p.total);
670 }
671
672 #[test]
673 fn the_largest_change_comes_first_in_either_direction() {
674 let d = diff(&parse(BASE).unwrap(), &parse(HEAD).unwrap());
675 let got: Vec<(&str, i128)> = d.iter().map(|d| (d.name.as_str(), d.change())).collect();
676 assert_eq!(
677 got,
678 [
679 ("mycli::render", 900),
680 ("mycli::parse_args", -300),
681 ("mycli::new_helper", 50),
682 ("mycli::gone", -40),
683 ]
684 );
685 let new = d.iter().find(|d| d.name == "mycli::new_helper").unwrap();
687 assert_eq!((new.base, new.head), (0, 50));
688 assert_eq!(new.file, "src/new.rs");
689 let gone = d.iter().find(|d| d.name == "mycli::gone").unwrap();
690 assert_eq!(gone.file, "src/old.rs");
691 }
692
693 #[test]
694 fn identical_profiles_have_no_changes() {
695 let p = parse(BASE).unwrap();
696 assert!(diff(&p, &p).is_empty());
697 }
698
699 #[test]
700 fn a_missing_summary_is_the_sum() {
701 let p = parse("events: Ir\nfl=a.c\nfn=f\n1 5\n2 7\n").unwrap();
702 assert_eq!(p.total, 12);
703 }
704
705 #[test]
706 fn compressed_names_resolve_to_their_definition() {
707 let text = "\
708events: Ir
709fl=(1) src/a.c
710fn=(1) alpha
7111 10
712fn=(2) beta
7132 20
714fl=(1)
715fn=(1)
7163 5
717";
718 let p = parse(text).unwrap();
719 assert_eq!(p.functions["alpha"].ir, 15);
720 assert_eq!(p.functions["beta"].ir, 20);
721 assert_eq!(p.functions["alpha"].files["src/a.c"], 15);
722 }
723
724 #[test]
727 fn a_parenthesised_name_is_a_name() {
728 let p = parse("events: Ir\nfl=???\nfn=(below main)\n0 9\n").unwrap();
729 assert_eq!(p.functions["(below main)"].ir, 9);
730 }
731
732 #[test]
733 fn a_reference_to_an_undefined_name_is_an_error() {
734 let err = parse("events: Ir\nfn=(7)\n1 1\n").unwrap_err();
735 assert!(format!("{err:#}").contains("(7)"), "{err:#}");
736 }
737
738 #[test]
741 fn the_cost_after_a_call_is_not_self_cost() {
742 let text = "\
743events: Ir
744fl=a.c
745fn=caller
7461 3
747cfn=callee
748calls=1 10
7491 100
7502 4
751fn=callee
75210 100
753";
754 let p = parse(text).unwrap();
755 assert_eq!(p.functions["caller"].ir, 7);
756 assert_eq!(p.functions["callee"].ir, 100);
757 }
758
759 #[test]
760 fn ir_is_found_among_other_events() {
761 let text = "events: Dr Ir Dw\nfl=a.c\nfn=f\n1 100 5 100\n2 100 6\nsummary: 999 11 999\n";
762 let p = parse(text).unwrap();
763 assert_eq!(p.functions["f"].ir, 11);
764 assert_eq!(p.total, 11);
765 }
766
767 #[test]
768 fn a_malformed_cost_names_its_line() {
769 let err = parse("events: Ir\nfn=f\n1 lots\n").unwrap_err();
770 assert!(format!("{err:#}").contains("line 3"), "{err:#}");
771 }
772
773 #[test]
774 fn a_file_without_events_is_not_a_profile() {
775 assert!(parse("hello\n").is_err());
776 }
777
778 fn origin(runner: &str) -> Origin {
779 Origin {
780 runner: runner.into(),
781 commit: Some("0123456789abcdef".into()),
782 bench: "startup".into(),
783 subject: "self".into(),
784 }
785 }
786
787 fn unrecorded(_: &Origin) -> Option<u64> {
789 None
790 }
791
792 #[test]
793 fn the_origin_is_read_back_from_the_description() {
794 let dir = tempfile::tempdir().unwrap();
795 let dest = path_for(dir.path(), "startup", "self").unwrap();
796 write(&dest, BASE.as_bytes(), &origin("gha-linux-x64")).unwrap();
797 let p = Profile::load(&dest).unwrap();
798 assert_eq!(p.origin(), Some(origin("gha-linux-x64")));
799 assert_eq!(p.runner().as_deref(), Some("gha-linux-x64"));
800 assert_eq!(p.total, parse(BASE).unwrap().total);
802 assert_eq!(parse(BASE).unwrap().origin(), None);
804 }
805
806 #[test]
808 fn an_origin_stays_on_its_own_lines() {
809 let dir = tempfile::tempdir().unwrap();
810 let dest = dir.path().join("p");
811 let o = Origin {
812 runner: "r\nfl=x\nfn=y\n1 999".into(),
813 ..origin("r")
814 };
815 write(&dest, BASE.as_bytes(), &o).unwrap();
816 let p = Profile::load(&dest).unwrap();
817 assert_eq!(p.total, 1_500);
818 assert!(!p.functions.contains_key("y"));
819 }
820
821 #[test]
822 fn a_name_that_is_not_a_plain_file_name_is_refused() {
823 let dir = Path::new("/p");
824 assert_eq!(
825 path_for(dir, "startup", "self").unwrap(),
826 Path::new("/p/startup/self.cachegrind.out")
827 );
828 for (bench, subject) in [
829 ("..", "x"),
830 ("a/b", "x"),
831 ("a", ""),
832 ("a", "."),
833 ("a", "b\\c"),
834 ("a\nb", "x"),
835 ("a", "x\r"),
836 ("a\0", "x"),
837 ] {
838 assert!(
839 path_for(dir, bench, subject).is_err(),
840 "{bench:?} {subject:?}"
841 );
842 }
843 }
844
845 #[test]
846 fn a_self_subject_is_labelled_by_its_benchmark() {
847 assert_eq!(label("startup/self.cachegrind.out"), "startup");
848 assert_eq!(
849 label("startup/hyperfine.cachegrind.out"),
850 "startup (hyperfine)"
851 );
852 assert_eq!(label("mine.cachegrind.out"), "mine");
853 }
854
855 #[test]
858 fn a_label_cannot_add_markdown() {
859 assert_eq!(
862 label("x\n## All clear/[ok](http:\\/e)<b>.cachegrind.out"),
863 "x\\\\n\\#\\# All clear (\\[ok\\](http:\\\\/e)\\<b\\>)"
864 );
865 assert_eq!(cell("a\nb`c|d"), "`` a\\nb`c\\|d ``");
868 }
869
870 #[test]
871 fn directories_pair_on_benchmark_and_subject() {
872 let (b, h) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
873 for (dir, text, subjects) in [
874 (&b, BASE, &["self", "only-base"][..]),
875 (&h, HEAD, &["self", "only-head"][..]),
876 ] {
877 for s in subjects {
878 write(
879 &path_for(dir.path(), "startup", s).unwrap(),
880 text.as_bytes(),
881 &origin("r"),
882 )
883 .unwrap();
884 }
885 }
886 let (pairs, unpaired) = load(b.path(), h.path()).unwrap();
887 assert_eq!(pairs.len(), 1);
888 assert_eq!(pairs[0].label, "startup");
889 assert_eq!(pairs[0].head.total, 2_110);
890 assert_eq!(unpaired.base, ["startup/only-base.cachegrind.out"]);
891 assert_eq!(unpaired.head, ["startup/only-head.cachegrind.out"]);
892 assert!(load(b.path(), &b.path().join("startup/self.cachegrind.out")).is_err());
893 }
894
895 #[test]
896 fn the_report_accounts_for_the_whole_change() {
897 let pair = Pair {
898 label: "startup".into(),
899 base: parse(BASE).unwrap(),
900 head: parse(HEAD).unwrap(),
901 };
902 let md = markdown(&[pair], &Unpaired::default(), 2, &unrecorded);
903 assert!(
904 md.contains("1,500 → 2,110 instructions (+610, **+40.67%**)"),
905 "{md}"
906 );
907 assert!(
908 md.contains("| `mycli::render` | **+900** | 100 | 1,000 | `src/render.rs` |"),
909 "{md}"
910 );
911 assert!(md.contains("| `mycli::parse_args` | **-300** |"), "{md}");
912 assert!(md.contains("| 2 more | +10 |"), "{md}");
914 assert!(!md.contains("WARNING"), "{md}");
915 }
916
917 #[test]
918 fn different_runners_are_called_out() {
919 let mut base = parse(BASE).unwrap();
920 let mut head = base.clone();
921 base.desc.push("tak runner: a".into());
922 head.desc.push("tak runner: b".into());
923 let pair = Pair {
924 label: "x".into(),
925 base,
926 head,
927 };
928 let md = markdown(&[pair], &Unpaired::default(), 10, &unrecorded);
929 assert!(
930 md.contains("different runner classes (`a` and `b`)"),
931 "{md}"
932 );
933 assert!(
934 md.contains("No function's instruction count changed."),
935 "{md}"
936 );
937 }
938
939 #[test]
943 fn a_profile_that_is_not_the_recorded_count_is_called_out() {
944 let with_origin = |text: &str| {
945 let mut p = parse(text).unwrap();
946 p.desc = vec![
947 "tak runner: r".into(),
948 "tak commit: 0123456789abcdef".into(),
949 "tak bench: startup".into(),
950 "tak subject: self".into(),
951 ];
952 p
953 };
954 let pair = Pair {
955 label: "startup".into(),
956 base: with_origin(BASE),
957 head: with_origin(HEAD),
958 };
959 let asked = std::cell::RefCell::new(Vec::new());
960 let recorded = |o: &Origin| {
962 asked.borrow_mut().push(o.clone());
963 Some(if asked.borrow().len() == 1 {
964 1_500
965 } else {
966 2_000
967 })
968 };
969 let md = markdown(&[pair], &Unpaired::default(), 10, &recorded);
970 assert!(
971 md.contains(
972 "The head profile totals 2,110 instructions, but the lowest count recorded \
973 for `0123456789ab` in git notes is 2,000."
974 ),
975 "{md}"
976 );
977 assert!(!md.contains("The base profile"), "{md}");
978 assert_eq!(asked.borrow()[0].bench, "startup");
979 assert_eq!(asked.borrow()[0].subject, "self");
980 }
981
982 #[test]
985 fn an_indented_line_is_read_like_any_other() {
986 let p = parse("events: Ir\n fl=a.c\n\tfn=f\n 1 5\n 2 7 \n summary: 12\n").unwrap();
987 assert_eq!(p.functions["f"].ir, 12);
988 assert_eq!(p.functions["f"].files["a.c"], 12);
989 }
990
991 #[test]
992 fn a_pipe_in_a_name_does_not_break_the_table() {
993 assert_eq!(cell("f::{{closure}}|x"), "`f::{{closure}}\\|x`");
994 }
995}