1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225
//! Iai-Callgrind is a benchmarking framework/harness which uses [Valgrind's
//! Callgrind](https://valgrind.org/docs/manual/cl-manual.html) to provide extremely accurate and
//! consistent measurements of Rust code, making it perfectly suited to run in environments like a
//! CI.
//!
//! # Features
//! - __Precision__: High-precision measurements allow you to reliably detect very small
//! optimizations of your code
//! - __Consistency__: Iai-Callgrind can take accurate measurements even in virtualized CI
//! environments
//! - __Performance__: Since Iai-Callgrind only executes a benchmark once, it is typically a lot
//! faster to run than benchmarks measuring the execution and wall time
//! - __Regression__: Iai-Callgrind reports the difference between benchmark runs to make it easy to
//! spot detailed performance regressions and improvements.
//! - __Profiling__: Iai-Callgrind generates a Callgrind profile of your code while benchmarking, so
//! you can use Callgrind-compatible tools like
//! [callgrind_annotate](https://valgrind.org/docs/manual/cl-manual.html#cl-manual.callgrind_annotate-options)
//! or the visualizer [kcachegrind](https://kcachegrind.github.io/html/Home.html) to analyze the
//! results in detail
//! - __Stable-compatible__: Benchmark your code without installing nightly Rust
//!
//! # Benchmarking
//!
//! `iai-callgrind` can be divided into two sections: Benchmarking the library and
//! its public functions and benchmarking of a crate's binary.
//!
//! ## Library Benchmarks
//!
//! Use this scheme of the [`main`] macro if you want to benchmark functions of your
//! crate's library.
//!
//! ### Important default behavior
//!
//! The environment variables are cleared before running a library benchmark. See also the
//! Configuration section below if you need to change that behavior.
//!
//! ### Quickstart
//!
//! ```rust
//! use iai_callgrind::{black_box, library_benchmark, library_benchmark_group, main};
//!
//! // Our function we want to test. Just assume this is a public function in your
//! // library.
//! fn bubble_sort(mut array: Vec<i32>) -> Vec<i32> {
//! for i in 0..array.len() {
//! for j in 0..array.len() - i - 1 {
//! if array[j + 1] < array[j] {
//! array.swap(j, j + 1);
//! }
//! }
//! }
//! array
//! }
//!
//! // This function is used to create a worst case array we want to sort with our
//! // implementation of bubble sort
//! fn setup_worst_case_array(start: i32) -> Vec<i32> {
//! if start.is_negative() {
//! (start..0).rev().collect()
//! } else {
//! (0..start).rev().collect()
//! }
//! }
//!
//! // The #[library_benchmark] attribute let's you define a benchmark function which you
//! // can later use in the `library_benchmark_groups!` macro.
//! #[library_benchmark]
//! fn bench_bubble_sort_empty() -> Vec<i32> {
//! // The `black_box` is needed to tell the compiler to not optimize what's inside
//! // black_box or else the benchmarks might return inaccurate results.
//! black_box(bubble_sort(black_box(vec![])))
//! }
//!
//! // This benchmark uses the `bench` attribute to setup benchmarks with different
//! // setups. The big advantage is, that the setup costs and event counts aren't
//! // attributed to the benchmark (and opposed to the old api we don't have to deal with
//! // callgrind arguments, toggles, ...)
//! #[library_benchmark]
//! #[bench::empty(vec![])]
//! #[bench::worst_case_6(vec![6, 5, 4, 3, 2, 1])]
//! // Function calls are fine too
//! #[bench::worst_case_4000(setup_worst_case_array(4000))]
//! // The argument of the benchmark function defines the type of the argument from the
//! // `bench` cases.
//! fn bench_bubble_sort(array: Vec<i32>) -> Vec<i32> {
//! // Note `array` is not put in a `black_box` because that's already done for you.
//! black_box(bubble_sort(array))
//! }
//!
//! // A group in which we can put all our benchmark functions
//! library_benchmark_group!(
//! name = bubble_sort_group;
//! benchmarks = bench_bubble_sort_empty, bench_bubble_sort
//! );
//!
//! # fn main() {
//! // Finally, the mandatory main! macro which collects all `library_benchmark_groups`.
//! // The main! macro creates a benchmarking harness and runs all the benchmarks defined
//! // in the groups and benches.
//! main!(library_benchmark_groups = bubble_sort_group);
//! # }
//! ```
//!
//! Note that it is important to annotate the benchmark functions with
//! [`#[library_benchmark]`](crate::library_benchmark).
//!
//! ### Configuration
//!
//! It's possible to configure some of the behavior of `iai-callgrind`. See the docs of
//! [`crate::LibraryBenchmarkConfig`] for more details. Configure library benchmarks at
//! top-level with the [`crate::main`] macro, at group level within the
//! [`crate::library_benchmark_group`], at [`crate::library_benchmark`] level
//!
//! and at `bench` level:
//!
//! ```rust
//! # use iai_callgrind::{LibraryBenchmarkConfig, library_benchmark};
//! #[library_benchmark]
//! #[bench::some_id(args = (1, 2), config = LibraryBenchmarkConfig::default())]
//! // ...
//! # fn some_func(first: u8, second: u8) -> u8 {
//! # first + second
//! # }
//! # fn main() {}
//! ```
//!
//! The config at `bench` level overwrites the config at `library_benchmark` level. The config at
//! `library_benchmark` level overwrites the config at group level and so on. Note that
//! configuration values like `envs` are additive and don't overwrite configuration values of higher
//! levels.
//!
//! See also the docs of [`crate::library_benchmark_group`]. The
//! [README](https://github.com/iai-callgrind/iai-callgrind) of this crate includes more explanations,
//! common recipes and some examples.
//!
//! ## Binary Benchmarks
//!
//! Use this scheme of the [`main`] macro to benchmark one or more binaries of your crate. If you
//! really like to, it's possible to benchmark any executable file in the PATH or any executable
//! specified with an absolute path. The documentation for setting up binary benchmarks with the
//! `binary_benchmark_group` macro can be found in the docs of [`crate::binary_benchmark_group`].
//!
//! ### Temporary Workspace and other important default behavior
//!
//! Per default, all binary benchmarks and the `before`, `after`, `setup` and `teardown` functions
//! are executed in a temporary directory. See [`crate::BinaryBenchmarkConfig::sandbox`] for a
//! deeper explanation and how to control and change this behavior. Also, the environment variables
//! of benchmarked binaries are cleared before the benchmark is run. See also
//! [`crate::BinaryBenchmarkConfig::env_clear`] for how to change this behavior.
//!
//! ### Quickstart
//!
//! Suppose your crate's binary is named `my-exe` and you have a fixtures directory in
//! `benches/fixtures` with a file `test1.txt` in it:
//!
//! ```rust
//! use iai_callgrind::{
//! main, binary_benchmark_group, BinaryBenchmarkConfig, BinaryBenchmarkGroup,
//! Run, Arg, Fixtures
//! };
//!
//! fn my_setup() {
//! println!("We can put code in here which will be run before each benchmark run");
//! }
//!
//! // We specify a cmd `"my-exe"` for the whole group which is a binary of our crate. This
//! // eliminates the need to specify a `cmd` for each `Run` later on and we can use the
//! // auto-discovery of a crate's binary at group level. We'll also use the `setup` argument
//! // to run a function before each of the benchmark runs.
//! binary_benchmark_group!(
//! name = my_exe_group;
//! setup = my_setup;
//! // This directory will be copied into the root of the sandbox (as `fixtures`)
//! config = BinaryBenchmarkConfig::default().fixtures(Fixtures::new("benches/fixtures"));
//! benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| setup_my_exe_group(group));
//!
//! // Working within a macro can be tedious sometimes so we moved the setup code into
//! // this method
//! fn setup_my_exe_group(group: &mut BinaryBenchmarkGroup) {
//! group
//! // Setup our first run doing something with our fixture `test1.txt`. The
//! // id (here `do foo with test1`) of an `Arg` has to be unique within the
//! // same group
//! .bench(Run::with_arg(Arg::new(
//! "do foo with test1",
//! ["--foo=fixtures/test1.txt"],
//! )))
//!
//! // Setup our second run with two positional arguments
//! .bench(Run::with_arg(Arg::new(
//! "positional arguments",
//! ["foo", "foo bar"],
//! )))
//!
//! // Our last run doesn't take an argument at all.
//! .bench(Run::with_arg(Arg::empty("no argument")));
//! }
//!
//! # fn main() {
//! // As last step specify all groups we want to benchmark in the main! macro argument
//! // `binary_benchmark_groups`. The main macro is always needed and finally expands
//! // to a benchmarking harness
//! main!(binary_benchmark_groups = my_exe_group);
//! # }
//! ```
//! ### Configuration
//!
//! Much like the configuration of library benchmarks (See above) it's possible to configure binary
//! benchmarks at top-level in the `main!` macro and at group-level in the
//! `binary_benchmark_groups!` with the `config = ...;` argument. In contrast to library benchmarks,
//! binary benchmarks can be configured at a lower and last level within [`Run`] directly.
//!
//! For further details see the section about binary benchmarks of the [`crate::main`] docs the docs
//! of [`crate::binary_benchmark_group`] and [`Run`]. Also, the
//! [README](https://github.com/iai-callgrind/iai-callgrind) of this crate includes some introductory
//! documentation with additional examples.
//!
//! ### Flamegraphs
//!
//! Flamegraphs are opt-in and can be created if you pass a [`FlamegraphConfig`] to the
//! [`BinaryBenchmarkConfig::flamegraph`], [`Run::flamegraph`] or
//! [`LibraryBenchmarkConfig::flamegraph`]. Callgrind flamegraphs are meant as a complement to
//! valgrind's visualization tools `callgrind_annotate` and `kcachegrind`.
//!
//! Callgrind flamegraphs show the inclusive costs for functions and a specific event type, much
//! like `callgrind_annotate` does but in a nicer (and clickable) way. Especially, differential
//! flamegraphs facilitate a deeper understanding of code sections which cause a bottleneck or a
//! performance regressions etc.
//!
//! The produced flamegraph svg files are located next to the respective callgrind output file in
//! the `target/iai` directory.
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
#![doc(test(attr(warn(unused))))]
#![doc(test(attr(allow(unused_extern_crates))))]
#![warn(missing_docs)]
#![warn(clippy::pedantic)]
#![warn(clippy::default_numeric_fallback)]
#![warn(clippy::else_if_without_else)]
#![warn(clippy::fn_to_numeric_cast_any)]
#![warn(clippy::get_unwrap)]
#![warn(clippy::if_then_some_else_none)]
#![warn(clippy::mixed_read_write_in_expression)]
#![warn(clippy::partial_pub_fields)]
#![warn(clippy::rest_pat_in_fully_bound_structs)]
#![warn(clippy::str_to_string)]
#![warn(clippy::string_to_string)]
#![warn(clippy::todo)]
#![warn(clippy::try_err)]
#![warn(clippy::undocumented_unsafe_blocks)]
#![warn(clippy::unneeded_field_pattern)]
#![allow(clippy::must_use_candidate)]
#![allow(clippy::return_self_not_must_use)]
#![allow(clippy::enum_glob_use)]
#![allow(clippy::module_name_repetitions)]
pub use bincode;
pub use iai_callgrind_macros::library_benchmark;
pub use iai_callgrind_runner::api::{Direction, EventKind, FlamegraphKind};
#[doc(hidden)]
pub mod internal;
mod macros;
use std::ffi::OsString;
use std::fmt::Display;
use std::path::PathBuf;
macro_rules! impl_traits {
($src:ty, $dst:ty) => {
impl From<$src> for $dst {
fn from(value: $src) -> Self {
value.0
}
}
impl From<&$src> for $dst {
fn from(value: &$src) -> Self {
value.0.clone()
}
}
impl From<&mut $src> for $dst {
fn from(value: &mut $src) -> Self {
value.0.clone()
}
}
impl AsRef<$src> for $src {
fn as_ref(&self) -> &$src {
self
}
}
};
}
/// The arguments needed for [`Run`] which are passed to the benchmarked binary
#[derive(Debug, Clone)]
pub struct Arg(internal::InternalArg);
/// An id for an [`Arg`] which can be used to produce unique ids from parameters
#[derive(Debug, Clone)]
pub struct BenchmarkId {
id: String,
}
/// The main configuration of a binary benchmark.
///
/// Currently it's only possible to pass additional arguments to valgrind's callgrind for all
/// benchmarks. See [`BinaryBenchmarkConfig::raw_callgrind_args`] for more details.
///
/// # Examples
///
/// ```rust,no_run
/// # use iai_callgrind::binary_benchmark_group;
/// # binary_benchmark_group!(name = some_group; benchmark = |group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::BinaryBenchmarkConfig;
///
/// iai_callgrind::main!(
/// config = BinaryBenchmarkConfig::default().raw_callgrind_args(["toggle-collect=something"]);
/// binary_benchmark_groups = some_group
/// );
/// ```
#[derive(Debug, Default, Clone)]
pub struct BinaryBenchmarkConfig(internal::InternalBinaryBenchmarkConfig);
/// The `BinaryBenchmarkGroup` lets you configure binary benchmark [`Run`]s
#[derive(Debug, Default, Clone)]
pub struct BinaryBenchmarkGroup(internal::InternalBinaryBenchmarkGroup);
/// Set the expected exit status of a binary benchmark
///
/// Per default, the benchmarked binary is expected to succeed, but if a benchmark is expected to
/// fail, setting this option is required.
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig, ExitWith};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().exit_with(ExitWith::Code(1));
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
#[derive(Debug, Clone)]
pub enum ExitWith {
/// Exit with success is similar to `ExitCode(0)`
Success,
/// Exit with failure is similar to setting the `ExitCode` to something different than `0`
Failure,
/// The exact `ExitCode` of the benchmark run
Code(i32),
}
/// A builder of `Fixtures` to specify the fixtures directory which will be copied into the sandbox
///
/// # Examples
///
/// ```rust
/// use iai_callgrind::Fixtures;
/// let fixtures: Fixtures = Fixtures::new("benches/fixtures");
/// ```
#[derive(Debug, Clone)]
pub struct Fixtures(internal::InternalFixtures);
/// The `FlamegraphConfig` which allows the customization of the created flamegraphs
///
/// Callgrind flamegraphs are very similar to `callgrind_annotate` output. In contrast to
/// `callgrind_annotate` text based output, the produced flamegraphs are svg files (located in the
/// `target/iai` directory) which can be viewed in a browser.
///
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{library_benchmark, library_benchmark_group};
/// use iai_callgrind::{LibraryBenchmarkConfig, FlamegraphConfig, main};
/// # #[library_benchmark]
/// # fn some_func() {}
/// # library_benchmark_group!(name = some_group; benchmarks = some_func);
/// # fn main() {
/// main!(
/// config = LibraryBenchmarkConfig::default()
/// .flamegraph(FlamegraphConfig::default());
/// library_benchmark_groups = some_group
/// );
/// # }
/// ```
#[derive(Debug, Clone, Default)]
pub struct FlamegraphConfig(internal::InternalFlamegraphConfig);
/// The main configuration of a library benchmark.
///
/// See [`LibraryBenchmarkConfig::raw_callgrind_args`] for more details.
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{library_benchmark, library_benchmark_group, LibraryBenchmarkConfig, main};
/// # #[library_benchmark]
/// # fn some_func() {}
/// # library_benchmark_group!(name = some_group; benchmarks = some_func);
/// # fn main() {
/// main!(
/// config = LibraryBenchmarkConfig::default()
/// .raw_callgrind_args(["toggle-collect=something"]);
/// library_benchmark_groups = some_group
/// );
/// # }
/// ```
#[derive(Debug, Default)]
pub struct LibraryBenchmarkConfig(internal::InternalLibraryBenchmarkConfig);
/// `Run` let's you set up and configure a benchmark run of a binary
#[derive(Debug, Default, Clone)]
pub struct Run(internal::InternalRun);
impl Arg {
/// Create a new `Arg`.
///
/// The `id` must be unique within the same group. It's also possible to use [`BenchmarkId`] as
/// an argument for the `id` if you want to create unique ids from a parameter.
///
/// An `Arg` can contain multiple arguments which are passed to the benchmarked binary as is. In
/// the case of no arguments at all, it's more convenient to use [`Arg::empty`].
///
/// # Examples
///
/// ```rust
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// use std::ffi::OsStr;
///
/// binary_benchmark_group!(
/// name = my_exe_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(Run::with_arg(Arg::new("foo", &["foo"])));
/// group.bench(Run::with_arg(Arg::new("foo bar", &["foo", "bar"])));
/// group.bench(Run::with_arg(Arg::new("os str foo", &[OsStr::new("foo")])));
/// }
/// );
/// # fn main() {
/// # my_exe_group::my_exe_group(&mut BinaryBenchmarkGroup::default());
/// # }
/// ```
///
/// Here's a short example which makes use of the [`BenchmarkId`] to generate unique ids for
/// each `Arg`:
///
/// ```rust
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run, BenchmarkId};
/// use std::ffi::OsStr;
///
/// binary_benchmark_group!(
/// name = my_exe_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// for i in 0..10 {
/// group.bench(Run::with_arg(
/// Arg::new(BenchmarkId::new("foo with", i), [format!("--foo={i}")])
/// ));
/// }
/// }
/// );
/// # fn main() {
/// # my_exe_group::my_exe_group(&mut BinaryBenchmarkGroup::default());
/// # }
pub fn new<T, I, U>(id: T, args: U) -> Self
where
T: Into<String>,
I: Into<OsString>,
U: IntoIterator<Item = I>,
{
Self(internal::InternalArg {
id: Some(id.into()),
args: args.into_iter().map(std::convert::Into::into).collect(),
})
}
/// Create a new `Arg` with no arguments for the benchmarked binary
///
/// See also [`Arg::new`]
///
/// # Examples
///
/// ```rust
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_exe_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(Run::with_arg(Arg::empty("empty foo")));
/// }
/// );
/// # fn main() {
/// # my_exe_group::my_exe_group(&mut BinaryBenchmarkGroup::default());
/// # }
pub fn empty<T>(id: T) -> Self
where
T: Into<String>,
{
Self(internal::InternalArg {
id: Some(id.into()),
args: vec![],
})
}
}
impl_traits!(Arg, internal::InternalArg);
impl BenchmarkId {
/// Create a new `BenchmarkId`.
///
/// Use [`BenchmarkId`] as an argument for the `id` of an [`Arg`] if you want to create unique
/// ids from a parameter.
///
/// # Examples
///
/// ```rust
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run, BenchmarkId};
/// use std::ffi::OsStr;
///
/// binary_benchmark_group!(
/// name = my_exe_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// for i in 0..10 {
/// group.bench(Run::with_arg(
/// Arg::new(BenchmarkId::new("foo with", i), [format!("--foo={i}")])
/// ));
/// }
/// }
/// );
/// # fn main() {
/// # my_exe_group::my_exe_group(&mut BinaryBenchmarkGroup::default());
/// # }
pub fn new<T, P>(id: T, parameter: P) -> Self
where
T: AsRef<str>,
P: Display,
{
Self {
id: format!("{}_{parameter}", id.as_ref()),
}
}
}
impl BinaryBenchmarkConfig {
/// Copy [`Fixtures`] into the sandbox (if enabled)
///
/// See also [`Fixtures`] for details about fixtures and
/// [`BinaryBenchmarkConfig::sandbox`] for details about the sandbox.
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig, Fixtures};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().fixtures(Fixtures::new("benches/fixtures"));
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn fixtures<T>(&mut self, value: T) -> &mut Self
where
T: Into<internal::InternalFixtures>,
{
self.0.fixtures = Some(value.into());
self
}
/// Configure benchmarks to run in a sandbox (Default: true)
///
/// Per default, all binary benchmarks and the `before`, `after`, `setup` and `teardown`
/// functions are executed in a temporary directory. This temporary directory will be created
/// and changed into before the `before` function is run and removed after the `after` function
/// has finished. [`BinaryBenchmarkConfig::fixtures`] let's you copy your fixtures into
/// that directory. If you want to access other directories within the benchmarked package's
/// directory, you need to specify absolute paths or set the sandbox argument to `false`.
///
/// Another reason for using a temporary directory as workspace is, that the length of the path
/// where a benchmark is executed may have an influence on the benchmark results. For example,
/// running the benchmark in your repository `/home/me/my/repository` and someone else's
/// repository located under `/home/someone/else/repository` may produce different results only
/// because the length of the first path is shorter. To run benchmarks as deterministic as
/// possible across different systems, the length of the path should be the same wherever the
/// benchmark is executed. This crate ensures this property by using the tempfile crate which
/// creates the temporary directory in `/tmp` with a random name of fixed length like
/// `/tmp/.tmp12345678`. This ensures that the length of the directory will be the same on all
/// unix hosts where the benchmarks are run.
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().sandbox(false);
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn sandbox(&mut self, value: bool) -> &mut Self {
self.0.sandbox = Some(value);
self
}
/// Pass arguments to valgrind's callgrind
///
/// It's not needed to pass the arguments with flags. Instead of `--collect-atstart=no` simply
/// write `collect-atstart=no`.
///
/// See also [Callgrind Command-line
/// Options](https://valgrind.org/docs/manual/cl-manual.html#cl-manual.options) for a full
/// overview of possible arguments.
///
/// # Examples
///
/// ```rust
/// use iai_callgrind::BinaryBenchmarkConfig;
///
/// let config = BinaryBenchmarkConfig::default()
/// .raw_callgrind_args(["collect-atstart=no", "toggle-collect=some::path"]);
/// ```
pub fn raw_callgrind_args<I, T>(&mut self, args: T) -> &mut Self
where
I: AsRef<str>,
T: IntoIterator<Item = I>,
{
self.0.raw_callgrind_args.extend(args);
self
}
/// Add an environment variable
///
/// These environment variables are available independently of the setting of
/// [`BinaryBenchmarkConfig::env_clear`].
///
/// # Examples
///
/// An example for a custom environment variable "FOO=BAR":
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().env("FOO", "BAR");
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn env<K, V>(&mut self, key: K, value: V) -> &mut Self
where
K: Into<OsString>,
V: Into<OsString>,
{
self.0.envs.push((key.into(), Some(value.into())));
self
}
/// Add multiple environment variable available in this `Run`
///
/// See also [`Run::env`] for more details.
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().envs([("FOO", "BAR"),("BAR", "BAZ")]);
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn envs<K, V, T>(&mut self, envs: T) -> &mut Self
where
K: Into<OsString>,
V: Into<OsString>,
T: IntoIterator<Item = (K, V)>,
{
self.0
.envs
.extend(envs.into_iter().map(|(k, v)| (k.into(), Some(v.into()))));
self
}
/// Specify a pass-through environment variable
///
/// Usually, the environment variables before running a library benchmark are cleared
/// but specifying pass-through variables makes this environment variable available to
/// the benchmark as it actually appeared in the root environment.
///
/// Pass-through environment variables are ignored if they don't exist in the root
/// environment.
///
/// # Examples
///
/// Here, we chose to pass-through the original value of the `HOME` variable:
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().pass_through_env("HOME");
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn pass_through_env<K>(&mut self, key: K) -> &mut Self
where
K: Into<OsString>,
{
self.0.envs.push((key.into(), None));
self
}
/// Specify multiple pass-through environment variables
///
/// See also [`LibraryBenchmarkConfig::pass_through_env`].
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().pass_through_envs(["HOME", "USER"]);
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn pass_through_envs<K, T>(&mut self, envs: T) -> &mut Self
where
K: Into<OsString>,
T: IntoIterator<Item = K>,
{
self.0
.envs
.extend(envs.into_iter().map(|k| (k.into(), None)));
self
}
/// If false, don't clear the environment variables before running the benchmark (Default: true)
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().env_clear(false);
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn env_clear(&mut self, value: bool) -> &mut Self {
self.0.env_clear = Some(value);
self
}
/// Set the directory of the benchmarked binary (Default: Unchanged)
///
/// Unchanged means, in the case of running with the sandbox enabled, the root of the sandbox.
/// In the case of running without sandboxing enabled, this'll be the root of the package
/// directory of the benchmark. If running the benchmark within the sandbox, and the path is
/// relative then this new directory must be contained in the sandbox.
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().current_dir("/tmp");
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
///
/// and the following will change the current directory to `fixtures` assuming it is
/// contained in the root of the sandbox
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().current_dir("fixtures");
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn current_dir<T>(&mut self, value: T) -> &mut Self
where
T: Into<PathBuf>,
{
self.0.current_dir = Some(value.into());
self
}
/// Set the start and entry point for event counting of the binary benchmark run
///
/// Per default, the counting of events starts right at the start of the binary and stops when
/// it finished execution. This'll include some os specific code which makes the executable
/// actually runnable. To focus on what is actually happening inside the benchmarked binary, it
/// may desirable to start the counting for example when entering the main function (but can be
/// any function) and stop counting when leaving the main function of the executable. The
/// following example will show how to do that.
///
/// # Examples
///
/// The `entry_point` could look like `my_exe::main` for a binary with the name `my-exe` (Note
/// that hyphens are replaced with an underscore).
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().entry_point("my_exe::main");
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
///
/// # About: How to find the right entry point
///
/// If unsure about the entry point, it is best to start without setting the entry point and
/// inspect the callgrind output file of the benchmark of interest. These are usually located
/// under `target/iai`. The file format is completely documented
/// [here](https://valgrind.org/docs/manual/cl-format.html). To focus on the lines of interest
/// for the entry point, these lines start with `fn=`.
///
/// The example above would include a line which would look like `fn=my_exe::main` with
/// information about the events below it and maybe some information about the exact location of
/// this function above it.
///
/// Now, you can set the entry point to what is following the `fn=` entry. To stick to the
/// example, this would be `my_exe::main`. Running the benchmark again should now show the event
/// counts of everything happening after entering the main function and before leaving it. If
/// the counts are `0` (and the main function is not empty), something went wrong and you have
/// to search the output file again for typos or similar.
pub fn entry_point<T>(&mut self, value: T) -> &mut Self
where
T: Into<String>,
{
self.0.entry_point = Some(value.into());
self
}
/// Set the expected exit status [`ExitWith`] of a benchmarked binary
///
/// Per default, the benchmarked binary is expected to succeed which is the equivalent of
/// [`ExitWith::Success`]. But, if a benchmark is expected to fail, setting this option is
/// required.
///
/// # Examples
///
/// If the benchmark is expected to fail with a specific exit code, for example `100`:
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig, ExitWith};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().exit_with(ExitWith::Code(100));
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
///
/// If a benchmark is expected to fail, but the exit code doesn't matter:
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig, ExitWith};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().exit_with(ExitWith::Failure);
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn exit_with<T>(&mut self, value: T) -> &mut Self
where
T: Into<internal::InternalExitWith>,
{
self.0.exit_with = Some(value.into());
self
}
/// Option to produce flamegraphs from callgrind output using the [`FlamegraphConfig`]
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig, FlamegraphConfig };
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().flamegraph(FlamegraphConfig::default());
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn flamegraph<T>(&mut self, config: T) -> &mut Self
where
T: Into<internal::InternalFlamegraphConfig>,
{
self.0.flamegraph = Some(config.into());
self
}
}
impl_traits!(
BinaryBenchmarkConfig,
internal::InternalBinaryBenchmarkConfig
);
impl BinaryBenchmarkGroup {
/// Specify a [`Run`] to benchmark a binary
///
/// You can specify a crate's binary either at group level with the simple name of the binary
/// (say `my-exe`) or at `bench` level with `env!("CARGO_BIN_EXE_my-exe")`. See examples.
///
/// See also [`Run`] for more details.
///
/// # Examples
///
/// If your crate has a binary `my-exe` (the `name` key of a `[[bin]]` entry in Cargo.toml),
/// specifying `"my-exe"` in the benchmark argument sets the command for all [`Run`]
/// arguments and it's sufficient to specify only [`Arg`] with [`Run::with_arg`]:
///
/// ```rust
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_exe_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(Run::with_arg(Arg::new("foo", &["foo"])));
/// }
/// );
/// # fn main() {
/// # my_exe_group::my_exe_group(&mut BinaryBenchmarkGroup::default());
/// # }
/// ```
///
/// Without the `command` at group level:
///
/// ```rust
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_exe_group;
/// benchmark = |group: &mut BinaryBenchmarkGroup| {
/// // Usually you should use `env!("CARGO_BIN_EXE_my-exe")` if `my-exe` is a binary
/// // of your crate
/// group.bench(Run::with_cmd("/path/to/my-exe", Arg::new("foo", &["foo"])));
/// }
/// );
/// # fn main() {
/// # my_exe_group::my_exe_group(&mut BinaryBenchmarkGroup::default());
/// # }
/// ```
pub fn bench<T>(&mut self, run: T) -> &mut Self
where
T: Into<internal::InternalRun>,
{
self.0.benches.push(run.into());
self
}
}
impl From<internal::InternalBinaryBenchmarkGroup> for BinaryBenchmarkGroup {
fn from(value: internal::InternalBinaryBenchmarkGroup) -> Self {
BinaryBenchmarkGroup(value)
}
}
impl_traits!(BinaryBenchmarkGroup, internal::InternalBinaryBenchmarkGroup);
impl Fixtures {
/// Create a new `Fixtures` struct
///
/// The fixtures argument specifies a path to a directory containing fixtures which you want to
/// be available for all benchmarks and the `before`, `after`, `setup` and `teardown` functions.
/// Per default, the fixtures directory will be copied as is into the sandbox directory of the
/// benchmark including symlinks. See [`Fixtures::follow_symlinks`] to change that behavior.
///
/// Relative paths are interpreted relative to the benchmarked package. In a multi-package
/// workspace this'll be the package name of the benchmark. Otherwise, it'll be the workspace
/// root.
///
/// # Examples
///
/// Here, the directory `benches/my_fixtures` (with a file `test_1.txt` in it) in the root of
/// the package under test will be copied into the temporary workspace (for example
/// `/tmp/.tmp12345678`). So,the benchmarks can access a fixture `test_1.txt` with a relative
/// path like `my_fixtures/test_1.txt`
///
/// ```rust
/// use iai_callgrind::Fixtures;
///
/// let fixtures: Fixtures = Fixtures::new("benches/my_fixtures");
/// ```
pub fn new<T>(path: T) -> Self
where
T: Into<PathBuf>,
{
Self(internal::InternalFixtures {
path: path.into(),
follow_symlinks: false,
})
}
/// If set to `true`, resolve symlinks in the [`Fixtures`] source directory
///
/// If set to `true` and the [`Fixtures`] directory contains symlinks, these symlinks are
/// resolved and instead of the symlink the target file or directory will be copied into the
/// fixtures directory.
///
/// # Examples
///
/// Here, the directory `benches/my_fixtures` (with a symlink `test_1.txt -> ../../test_1.txt`
/// in it) in the root of the package under test will be copied into the sandbox directory
/// (for example `/tmp/.tmp12345678`). Since `follow_symlink` is `true`, the benchmarks can
/// access a fixture `test_1.txt` with a relative path like `my_fixtures/test_1.txt`
///
/// ```rust
/// use iai_callgrind::Fixtures;
///
/// let fixtures: &mut Fixtures = Fixtures::new("benches/my_fixtures").follow_symlinks(true);
/// ```
pub fn follow_symlinks(&mut self, value: bool) -> &mut Self {
self.0.follow_symlinks = value;
self
}
}
impl_traits!(Fixtures, internal::InternalFixtures);
impl FlamegraphConfig {
/// Option to change the [`FlamegraphKind`]
///
/// The default is [`FlamegraphKind::All`].
///
/// # Examples
///
/// For example, to only create a differential flamegraph:
///
/// ```
/// use iai_callgrind::{FlamegraphConfig, FlamegraphKind};
///
/// let config = FlamegraphConfig::default().kind(FlamegraphKind::Differential);
/// ```
pub fn kind(&mut self, kind: FlamegraphKind) -> &mut Self {
self.0.kind = Some(kind);
self
}
/// Negate the differential flamegraph [`FlamegraphKind::Differential`]
///
/// The default is `false`.
///
/// Instead of showing the differential flamegraph from the viewing angle of what has happened
/// the negated differential flamegraph shows what will happen. Especially, this allows to see
/// vanished event lines (in blue) for example because the underlying code has improved and
/// removed an unnecessary function call.
///
/// See also [Differential Flame
/// Graphs](https://www.brendangregg.com/blog/2014-11-09/differential-flame-graphs.html) from
/// Brendan Gregg's Blog.
///
/// # Examples
///
/// ```
/// use iai_callgrind::{FlamegraphConfig, FlamegraphKind};
///
/// let config = FlamegraphConfig::default().negate_differential(true);
/// ```
pub fn negate_differential(&mut self, negate_differential: bool) -> &mut Self {
self.0.negate_differential = Some(negate_differential);
self
}
/// Normalize the differential flamegraph
///
/// This'll make the first profile event count to match the second. This'll help in situations
/// when everything looks read (or blue) to get a balanced profile with the full red/blue
/// spectrum
///
/// # Examples
///
/// ```
/// use iai_callgrind::{FlamegraphConfig, FlamegraphKind};
///
/// let config = FlamegraphConfig::default().normalize_differential(true);
/// ```
pub fn normalize_differential(&mut self, normalize_differential: bool) -> &mut Self {
self.0.normalize_differential = Some(normalize_differential);
self
}
/// One or multiple [`EventKind`] for which a flamegraph is going to be created.
///
/// The default is [`EventKind::EstimatedCycles`]
///
/// Currently, flamegraph creation is limited to one flamegraph for each [`EventKind`] and
/// there's no way to merge all event kinds into a single flamegraph.
///
/// Note it is an error to specify a [`EventKind`] which isn't recorded by callgrind. See the
/// docs of the variants of [`EventKind`] which callgrind option is needed to create a record
/// for it. See also the [Callgrind
/// Documentation](https://valgrind.org/docs/manual/cl-manual.html#cl-manual.options). The
/// [`EventKind`]s recorded by callgrind which are always available:
///
/// * [`EventKind::Ir`]
/// * [`EventKind::Dr`]
/// * [`EventKind::Dw`]
/// * [`EventKind::I1mr`]
/// * [`EventKind::ILmr`]
/// * [`EventKind::D1mr`]
/// * [`EventKind::DLmr`]
/// * [`EventKind::D1mw`]
/// * [`EventKind::DLmw`]
///
/// Additionally, the following derived `EventKinds` are available:
///
/// * [`EventKind::L1hits`]
/// * [`EventKind::LLhits`]
/// * [`EventKind::RamHits`]
/// * [`EventKind::TotalRW`]
/// * [`EventKind::EstimatedCycles`]
///
/// # Examples
///
/// ```
/// use iai_callgrind::{EventKind, FlamegraphConfig};
///
/// let config =
/// FlamegraphConfig::default().event_kinds([EventKind::EstimatedCycles, EventKind::Ir]);
/// ```
pub fn event_kinds<T>(&mut self, event_kinds: T) -> &mut Self
where
T: IntoIterator<Item = EventKind>,
{
self.0.event_kinds = Some(event_kinds.into_iter().collect());
self
}
/// Set the [`Direction`] in which the flamegraph should grow.
///
/// The default is [`Direction::TopToBottom`].
///
/// # Examples
///
/// For example to change the default
///
/// ```
/// use iai_callgrind::{Direction, FlamegraphConfig};
///
/// let config = FlamegraphConfig::default().direction(Direction::BottomToTop);
/// ```
pub fn direction(&mut self, direction: Direction) -> &mut Self {
self.0.direction = Some(direction);
self
}
/// Overwrite the default title of the final flamegraph
///
/// # Examples
///
/// ```
/// use iai_callgrind::{Direction, FlamegraphConfig};
///
/// let config = FlamegraphConfig::default().title("My flamegraph title".to_owned());
/// ```
pub fn title(&mut self, title: String) -> &mut Self {
self.0.title = Some(title);
self
}
/// Overwrite the default subtitle of the final flamegraph
///
/// # Examples
///
/// ```
/// use iai_callgrind::FlamegraphConfig;
///
/// let config = FlamegraphConfig::default().subtitle("My flamegraph subtitle".to_owned());
/// ```
pub fn subtitle(&mut self, subtitle: String) -> &mut Self {
self.0.subtitle = Some(subtitle);
self
}
/// Set the minimum width (in pixels) for which event lines are going to be shown.
///
/// The default is `0.1`
///
/// To show all events, set the `min_width` to `0f64`.
///
/// # Examples
///
/// ```
/// use iai_callgrind::FlamegraphConfig;
///
/// let config = FlamegraphConfig::default().min_width(0f64);
/// ```
pub fn min_width(&mut self, min_width: f64) -> &mut Self {
self.0.min_width = Some(min_width);
self
}
}
impl_traits!(FlamegraphConfig, internal::InternalFlamegraphConfig);
impl From<ExitWith> for internal::InternalExitWith {
fn from(value: ExitWith) -> Self {
match value {
ExitWith::Success => Self::Success,
ExitWith::Failure => Self::Failure,
ExitWith::Code(c) => Self::Code(c),
}
}
}
impl From<&ExitWith> for internal::InternalExitWith {
fn from(value: &ExitWith) -> Self {
match value {
ExitWith::Success => Self::Success,
ExitWith::Failure => Self::Failure,
ExitWith::Code(c) => Self::Code(*c),
}
}
}
impl LibraryBenchmarkConfig {
/// Create a new `LibraryBenchmarkConfig` with raw callgrind arguments
///
/// See also [`LibraryBenchmarkConfig::raw_callgrind_args`].
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{library_benchmark, library_benchmark_group, LibraryBenchmarkConfig, main};
/// # #[library_benchmark]
/// # fn some_func() {}
/// # library_benchmark_group!(name = some_group; benchmarks = some_func);
/// # fn main() {
/// main!(
/// config =
/// LibraryBenchmarkConfig::with_raw_callgrind_args(["toggle-collect=something"]);
/// library_benchmark_groups = some_group
/// );
/// # }
/// ```
pub fn with_raw_callgrind_args<I, T>(args: T) -> Self
where
I: AsRef<str>,
T: IntoIterator<Item = I>,
{
Self(internal::InternalLibraryBenchmarkConfig {
env_clear: None,
raw_callgrind_args: internal::InternalRawCallgrindArgs::new(args),
envs: vec![],
flamegraph: None,
})
}
/// Add callgrind arguments to this `LibraryBenchmarkConfig`
///
/// The arguments don't need to start with a flag: `--toggle-collect=some` or
/// `toggle-collect=some` are both understood.
///
/// Not all callgrind arguments are understood by `iai-callgrind` or cause problems in
/// `iai-callgrind` if they would be applied. `iai-callgrind` will issue a warning in
/// such cases. Some of the defaults can be overwritten. The default settings are:
///
/// * `--I1=32768,8,64`
/// * `--D1=32768,8,64`
/// * `--LL=8388608,16,64`
/// * `--cache-sim=yes` (can't be changed)
/// * `--toggle-collect=*BENCHMARK_FILE::BENCHMARK_FUNCTION` (this first toggle can't
/// be changed)
/// * `--collect-atstart=no` (overwriting this setting will have no effect)
/// * `--compress-pos=no`
/// * `--compress-strings=no`
///
/// Note that `toggle-collect` is an array and the entry point for library benchmarks
/// is the benchmark function. This default toggle switches event counting on when
/// entering this benchmark function and off when leaving it. So, additional toggles
/// for example matching a function within the benchmark function will switch the
/// event counting off when entering the matched function and on again when leaving
/// it!
///
/// See also [Callgrind Command-line
/// Options](https://valgrind.org/docs/manual/cl-manual.html#cl-manual.options)
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{library_benchmark, library_benchmark_group, LibraryBenchmarkConfig, main};
/// # #[library_benchmark]
/// # fn some_func() {}
/// # library_benchmark_group!(name = some_group; benchmarks = some_func);
/// # fn main() {
/// main!(
/// config = LibraryBenchmarkConfig::default()
/// .raw_callgrind_args(["toggle-collect=something"]);
/// library_benchmark_groups = some_group
/// );
/// # }
/// ```
pub fn raw_callgrind_args<I, T>(&mut self, args: T) -> &mut Self
where
I: AsRef<str>,
T: IntoIterator<Item = I>,
{
self.raw_callgrind_args_iter(args);
self
}
/// Add elements of an iterator over callgrind arguments to this `LibraryBenchmarkConfig`
///
/// See also [`LibraryBenchmarkConfig::raw_callgrind_args`]
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{library_benchmark, library_benchmark_group, LibraryBenchmarkConfig, main};
/// # #[library_benchmark]
/// # fn some_func() {}
/// # library_benchmark_group!(name = some_group; benchmarks = some_func);
/// # fn main() {
/// main!(
/// config = LibraryBenchmarkConfig::default()
/// .raw_callgrind_args_iter(["toggle-collect=something"].iter());
/// library_benchmark_groups = some_group
/// );
/// # }
/// ```
pub fn raw_callgrind_args_iter<I, T>(&mut self, args: T) -> &mut Self
where
I: AsRef<str>,
T: IntoIterator<Item = I>,
{
self.0.raw_callgrind_args.extend(args);
self
}
/// Clear the environment variables before running a benchmark (Default: true)
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{library_benchmark, library_benchmark_group, LibraryBenchmarkConfig, main};
/// # #[library_benchmark]
/// # fn some_func() {}
/// # library_benchmark_group!(name = some_group; benchmarks = some_func);
/// # fn main() {
/// main!(
/// config = LibraryBenchmarkConfig::default().env_clear(false);
/// library_benchmark_groups = some_group
/// );
/// # }
/// ```
pub fn env_clear(&mut self, value: bool) -> &mut Self {
self.0.env_clear = Some(value);
self
}
/// Add an environment variables which will be available in library benchmarks
///
/// These environment variables are available independently of the setting of
/// [`LibraryBenchmarkConfig::env_clear`].
///
/// # Examples
///
/// An example for a custom environment variable, available in all benchmarks:
///
/// ```rust
/// # use iai_callgrind::{library_benchmark, library_benchmark_group, LibraryBenchmarkConfig, main};
/// # #[library_benchmark]
/// # fn some_func() {}
/// # library_benchmark_group!(name = some_group; benchmarks = some_func);
/// # fn main() {
/// main!(
/// config = LibraryBenchmarkConfig::default().env("FOO", "BAR");
/// library_benchmark_groups = some_group
/// );
/// # }
/// ```
pub fn env<K, V>(&mut self, key: K, value: V) -> &mut Self
where
K: Into<OsString>,
V: Into<OsString>,
{
self.0.envs.push((key.into(), Some(value.into())));
self
}
/// Add multiple environment variables which will be available in library benchmarks
///
/// See also [`LibraryBenchmarkConfig::env`] for more details.
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{library_benchmark, library_benchmark_group, LibraryBenchmarkConfig, main};
/// # #[library_benchmark]
/// # fn some_func() {}
/// # library_benchmark_group!(name = some_group; benchmarks = some_func);
/// # fn main() {
/// main!(
/// config =
/// LibraryBenchmarkConfig::default().envs([("MY_CUSTOM_VAR", "SOME_VALUE"), ("FOO", "BAR")]);
/// library_benchmark_groups = some_group
/// );
/// # }
/// ```
pub fn envs<K, V, T>(&mut self, envs: T) -> &mut Self
where
K: Into<OsString>,
V: Into<OsString>,
T: IntoIterator<Item = (K, V)>,
{
self.0
.envs
.extend(envs.into_iter().map(|(k, v)| (k.into(), Some(v.into()))));
self
}
/// Specify a pass-through environment variable
///
/// Usually, the environment variables before running a library benchmark are cleared
/// but specifying pass-through variables makes this environment variable available to
/// the benchmark as it actually appeared in the root environment.
///
/// Pass-through environment variables are ignored if they don't exist in the root
/// environment.
///
/// # Examples
///
/// Here, we chose to pass-through the original value of the `HOME` variable:
///
/// ```rust
/// # use iai_callgrind::{library_benchmark, library_benchmark_group, LibraryBenchmarkConfig, main};
/// # #[library_benchmark]
/// # fn some_func() {}
/// # library_benchmark_group!(name = some_group; benchmarks = some_func);
/// # fn main() {
/// main!(
/// config = LibraryBenchmarkConfig::default().pass_through_env("HOME");
/// library_benchmark_groups = some_group
/// );
/// # }
/// ```
pub fn pass_through_env<K>(&mut self, key: K) -> &mut Self
where
K: Into<OsString>,
{
self.0.envs.push((key.into(), None));
self
}
/// Specify multiple pass-through environment variables
///
/// See also [`LibraryBenchmarkConfig::pass_through_env`].
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{library_benchmark, library_benchmark_group, LibraryBenchmarkConfig, main};
/// # #[library_benchmark]
/// # fn some_func() {}
/// # library_benchmark_group!(name = some_group; benchmarks = some_func);
/// # fn main() {
/// main!(
/// config = LibraryBenchmarkConfig::default().pass_through_envs(["HOME", "USER"]);
/// library_benchmark_groups = some_group
/// );
/// # }
/// ```
pub fn pass_through_envs<K, T>(&mut self, envs: T) -> &mut Self
where
K: Into<OsString>,
T: IntoIterator<Item = K>,
{
self.0
.envs
.extend(envs.into_iter().map(|k| (k.into(), None)));
self
}
/// Option to produce flamegraphs from callgrind output using the [`FlamegraphConfig`]
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{library_benchmark, library_benchmark_group};
/// use iai_callgrind::{LibraryBenchmarkConfig, main, FlamegraphConfig};
/// # #[library_benchmark]
/// # fn some_func() {}
/// # library_benchmark_group!(name = some_group; benchmarks = some_func);
/// # fn main() {
/// main!(
/// config = LibraryBenchmarkConfig::default().flamegraph(FlamegraphConfig::default());
/// library_benchmark_groups = some_group
/// );
/// # }
/// ```
pub fn flamegraph<T>(&mut self, config: T) -> &mut Self
where
T: Into<internal::InternalFlamegraphConfig>,
{
self.0.flamegraph = Some(config.into());
self
}
}
impl_traits!(
LibraryBenchmarkConfig,
internal::InternalLibraryBenchmarkConfig
);
impl Run {
/// Create a new `Run` with a `cmd` and [`Arg`]
///
/// A `cmd` specified here overwrites a `cmd` at group level.
///
/// Unlike to a `cmd` specified at group level, there is no auto-discovery of the executables of
/// a crate, so a crate's binary (say `my-exe`) has to be specified with
/// `env!("CARGO_BIN_EXE_my-exe")`.
///
/// Although not the main purpose of iai-callgrind, it's possible to benchmark any executable in
/// the PATH or specified with an absolute path.
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |group: &mut BinaryBenchmarkGroup| {
/// // Usually you should use `env!("CARGO_BIN_EXE_my-exe")` if `my-exe` is a binary
/// // of your crate
/// group.bench(Run::with_cmd("/path/to/my-exe", Arg::new("foo", &["foo"])));
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn with_cmd<T, U>(cmd: T, arg: U) -> Self
where
T: AsRef<str>,
U: Into<internal::InternalArg>,
{
let cmd = cmd.as_ref();
Self(internal::InternalRun {
cmd: Some(internal::InternalCmd {
display: cmd.to_owned(),
cmd: cmd.to_owned(),
}),
args: vec![arg.into()],
config: internal::InternalBinaryBenchmarkConfig::default(),
})
}
/// Create a new `Run` with a `cmd` and multiple [`Arg`]
///
/// See also [`Run::with_cmd`]
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |group: &mut BinaryBenchmarkGroup| {
/// group.bench(Run::with_cmd_args("/path/to/my-exe", [
/// Arg::empty("empty foo"),
/// Arg::new("foo", &["foo"]),
/// ]));
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn with_cmd_args<T, I, U>(cmd: T, args: U) -> Self
where
T: AsRef<str>,
I: Into<internal::InternalArg>,
U: IntoIterator<Item = I>,
{
let cmd = cmd.as_ref();
Self(internal::InternalRun {
cmd: Some(internal::InternalCmd {
display: cmd.to_owned(),
cmd: cmd.to_owned(),
}),
args: args.into_iter().map(std::convert::Into::into).collect(),
config: internal::InternalBinaryBenchmarkConfig::default(),
})
}
/// Create a new `Run` with an [`Arg`]
///
/// If a `cmd` is already specified at group level, there is no need to specify a `cmd` again
/// (for example with [`Run::with_cmd`]). This method let's you specify a single [`Arg`] to
/// run with the `cmd` specified at group level.
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(Run::with_arg(Arg::new("foo", &["foo"])));
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn with_arg<T>(arg: T) -> Self
where
T: Into<internal::InternalArg>,
{
Self(internal::InternalRun {
cmd: None,
args: vec![arg.into()],
config: internal::InternalBinaryBenchmarkConfig::default(),
})
}
/// Create a new `Run` with multiple [`Arg`]
///
/// Specifying multiple [`Arg`] arguments is actually just a short-hand for specifying multiple
/// [`Run`]s with the same configuration and environment variables.
///
/// ```rust
/// use iai_callgrind::{Arg, BinaryBenchmarkGroup, Run};
///
/// # let mut group1: BinaryBenchmarkGroup = BinaryBenchmarkGroup::default();
/// # let mut group2: BinaryBenchmarkGroup = BinaryBenchmarkGroup::default();
/// fn func1(group1: &mut BinaryBenchmarkGroup) {
/// group1.bench(Run::with_args([
/// Arg::empty("empty foo"),
/// Arg::new("foo", &["foo"]),
/// ]));
/// }
///
/// // This is actually the same as above in group1
/// fn func2(group2: &mut BinaryBenchmarkGroup) {
/// group2.bench(Run::with_arg(Arg::empty("empty foo")));
/// group2.bench(Run::with_arg(Arg::new("foo", &["foo"])));
/// }
/// # func1(&mut group1);
/// # func2(&mut group2);
/// ```
///
/// See also [`Run::with_arg`].
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(Run::with_args([
/// Arg::empty("empty foo"),
/// Arg::new("foo", &["foo"])
/// ]));
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn with_args<I, T>(args: T) -> Self
where
I: Into<internal::InternalArg>,
T: IntoIterator<Item = I>,
{
Self(internal::InternalRun {
cmd: None,
args: args.into_iter().map(std::convert::Into::into).collect(),
config: internal::InternalBinaryBenchmarkConfig::default(),
})
}
/// Add an additional [`Arg`] to the current `Run`
///
/// See also [`Run::with_args`] for more details about a [`Run`] with multiple [`Arg`]
/// arguments.
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(
/// Run::with_arg(Arg::empty("empty foo"))
/// .arg(Arg::new("foo", &["foo"]))
/// );
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn arg<T>(&mut self, arg: T) -> &mut Self
where
T: Into<internal::InternalArg>,
{
self.0.args.push(arg.into());
self
}
/// Add multiple additional [`Arg`] arguments to the current `Run`
///
/// See also [`Run::with_args`] for more details about a [`Run`] with multiple [`Arg`]
/// arguments.
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(
/// Run::with_arg(Arg::empty("empty foo"))
/// .args([
/// Arg::new("foo", &["foo"]),
/// Arg::new("bar", &["bar"])
/// ])
/// );
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn args<I, T>(&mut self, args: T) -> &mut Self
where
I: Into<internal::InternalArg>,
T: IntoIterator<Item = I>,
{
self.0
.args
.extend(args.into_iter().map(std::convert::Into::into));
self
}
/// Add an environment variable available in this `Run`
///
/// These environment variables are available independently of the setting of
/// [`Run::env_clear`].
///
/// # Examples
///
/// An example for a custom environment variable "FOO=BAR":
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(
/// Run::with_arg(Arg::empty("empty foo")).env("FOO", "BAR")
/// );
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
pub fn env<K, V>(&mut self, key: K, value: V) -> &mut Self
where
K: Into<OsString>,
V: Into<OsString>,
{
self.0.config.envs.push((key.into(), Some(value.into())));
self
}
/// Add multiple environment variable available in this `Run`
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(
/// Run::with_arg(Arg::empty("empty foo"))
/// .envs([("FOO", "BAR"), ("BAR", "BAZ")])
/// );
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
pub fn envs<K, V, T>(&mut self, envs: T) -> &mut Self
where
K: Into<OsString>,
V: Into<OsString>,
T: IntoIterator<Item = (K, V)>,
{
self.0
.config
.envs
.extend(envs.into_iter().map(|(k, v)| (k.into(), Some(v.into()))));
self
}
/// Specify a pass-through environment variable
///
/// See also [`BinaryBenchmarkConfig::pass_through_env`]
///
/// # Examples
///
/// Here, we chose to pass-through the original value of the `HOME` variable:
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(
/// Run::with_arg(Arg::empty("empty foo"))
/// .pass_through_env("HOME")
/// );
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn pass_through_env<K>(&mut self, key: K) -> &mut Self
where
K: Into<OsString>,
{
self.0.config.envs.push((key.into(), None));
self
}
/// Specify multiple pass-through environment variables
///
/// See also [`BinaryBenchmarkConfig::pass_through_env`].
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(
/// Run::with_arg(Arg::empty("empty foo"))
/// .pass_through_envs(["HOME", "USER"])
/// );
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn pass_through_envs<K, T>(&mut self, envs: T) -> &mut Self
where
K: Into<OsString>,
T: IntoIterator<Item = K>,
{
self.0
.config
.envs
.extend(envs.into_iter().map(|k| (k.into(), None)));
self
}
/// If false, don't clear the environment variables before running the benchmark (Default: true)
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(
/// Run::with_arg(Arg::empty("empty foo"))
/// .env_clear(false)
/// );
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn env_clear(&mut self, value: bool) -> &mut Self {
self.0.config.env_clear = Some(value);
self
}
/// Set the directory of the benchmarked binary (Default: Unchanged)
///
/// See also [`BinaryBenchmarkConfig::current_dir`]
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(
/// Run::with_arg(Arg::empty("empty foo"))
/// .current_dir("/tmp")
/// );
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
///
/// and the following will change the current directory to `fixtures` assuming it is
/// contained in the root of the sandbox
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run, BinaryBenchmarkConfig, Fixtures};
///
/// binary_benchmark_group!(
/// name = my_group;
/// config = BinaryBenchmarkConfig::default().fixtures(Fixtures::new("fixtures"));
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(
/// Run::with_arg(Arg::empty("empty foo"))
/// .current_dir("fixtures")
/// );
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn current_dir<T>(&mut self, value: T) -> &mut Self
where
T: Into<PathBuf>,
{
self.0.config.current_dir = Some(value.into());
self
}
/// Set the start and entry point for event counting of the binary benchmark run
///
/// See also [`BinaryBenchmarkConfig::entry_point`].
///
/// # Examples
///
/// The `entry_point` could look like `my_exe::main` for a binary with the name `my-exe` (Note
/// that hyphens are replaced with an underscore).
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(
/// Run::with_arg(Arg::empty("empty foo"))
/// .entry_point("my_exe::main")
/// );
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn entry_point<T>(&mut self, value: T) -> &mut Self
where
T: Into<String>,
{
self.0.config.entry_point = Some(value.into());
self
}
/// Set the expected exit status [`ExitWith`] of a benchmarked binary
///
/// See also [`BinaryBenchmarkConfig::exit_with`]
///
/// # Examples
///
/// If the benchmark is expected to fail with a specific exit code, for example `100`:
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run, ExitWith};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(
/// Run::with_arg(Arg::empty("empty foo"))
/// .exit_with(ExitWith::Code(100))
/// );
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
///
/// If a benchmark is expected to fail, but the exit code doesn't matter:
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run, ExitWith};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(
/// Run::with_arg(Arg::empty("empty foo"))
/// .exit_with(ExitWith::Failure)
/// );
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn exit_with<T>(&mut self, value: T) -> &mut Self
where
T: Into<internal::InternalExitWith>,
{
self.0.config.exit_with = Some(value.into());
self
}
/// Pass arguments to valgrind's callgrind at `Run` level
///
/// See also [`BinaryBenchmarkConfig::raw_callgrind_args`]
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(
/// Run::with_arg(Arg::empty("empty foo"))
/// .raw_callgrind_args(["collect-atstart=no", "toggle-collect=some::path"])
/// );
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn raw_callgrind_args<I, T>(&mut self, args: T) -> &mut Self
where
I: AsRef<str>,
T: IntoIterator<Item = I>,
{
self.0.config.raw_callgrind_args.extend(args);
self
}
/// Option to produce flamegraphs from callgrind output using the [`FlamegraphConfig`]
///
/// See also [`BinaryBenchmarkConfig::flamegraph`]
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, Arg, BinaryBenchmarkGroup, Run, FlamegraphConfig};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmark = |"my-exe", group: &mut BinaryBenchmarkGroup| {
/// group.bench(
/// Run::with_arg(Arg::empty("empty foo"))
/// .flamegraph(FlamegraphConfig::default())
/// );
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn flamegraph<T>(&mut self, config: T) -> &mut Self
where
T: Into<internal::InternalFlamegraphConfig>,
{
self.0.config.flamegraph = Some(config.into());
self
}
}
impl_traits!(Run, internal::InternalRun);
impl From<BenchmarkId> for String {
fn from(value: BenchmarkId) -> Self {
value.id
}
}
/// A function that is opaque to the optimizer, used to prevent the compiler from
/// optimizing away computations in a benchmark.
///
/// This variant is stable-compatible, but it may cause some performance overhead
/// or fail to prevent code from being eliminated.
pub fn black_box<T>(dummy: T) -> T {
// SAFETY: The safety conditions for read_volatile and forget are satisfied
unsafe {
let ret = std::ptr::read_volatile(&dummy);
std::mem::forget(dummy);
ret
}
}