iai_callgrind/bin_bench.rs
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 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834
use std::ffi::{OsStr, OsString};
use std::fmt::Display;
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::time::Duration;
use derive_more::AsRef;
use iai_callgrind_macros::IntoInner;
use iai_callgrind_runner::api::RawArgs;
use crate::{internal, DelayKind, Stdin, Stdio};
/// [low level api](`crate::binary_benchmark_group`) only: Create a new benchmark id
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BenchmarkId(String);
/// The configuration of a binary benchmark
///
/// The [`BinaryBenchmarkConfig`] can be specified at multiple levels and configures the benchmarks
/// at this level. For example a [`BinaryBenchmarkConfig`] at (`main`)[`crate::main`] level
/// configures all benchmarks. A configuration at [`group`](crate::binary_benchmark_group) level
/// configures all benchmarks in this group inheriting the configuration of the `main` level and if
/// not specified otherwise overwrites the values of the `main` configuration if the option is
/// specified in both [`BinaryBenchmarkConfig`]s. The deeper levels are the
/// (`#[binary_benchmark] attribute`)[`crate::binary_benchmark`], then `#[bench]` and the
/// `#[benches]` attribute.
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::binary_benchmark_group;
/// # binary_benchmark_group!(name = some_group; benchmarks = |_group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{BinaryBenchmarkConfig, main};
///
/// main!(
/// config = BinaryBenchmarkConfig::default().callgrind_args(["toggle-collect=something"]);
/// binary_benchmark_groups = some_group
/// );
/// ```
#[derive(Debug, Default, Clone, IntoInner, AsRef)]
pub struct BinaryBenchmarkConfig(internal::InternalBinaryBenchmarkConfig);
/// [low level api](`crate::binary_benchmark_group`) only: The top level struct to add binary
/// benchmarks to
///
/// This struct doesn't need to be instantiated by yourself. It is passed as mutable reference to
/// the expression in `benchmarks`.
///
/// ```rust
/// use iai_callgrind::binary_benchmark_group;
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = |_group: &mut BinaryBenchmarkGroup| {
/// // Access the BinaryBenchmarkGroup with the identifier `group` to add benchmarks to the
/// // group.
/// //
/// // group.binary_benchmark(/* BinaryBenchmark::new(...) */);
/// }
/// );
/// ```
#[derive(Debug, Default, PartialEq, Clone)]
pub struct BinaryBenchmarkGroup {
/// All [`BinaryBenchmark`]s
pub binary_benchmarks: Vec<BinaryBenchmark>,
}
/// [low level api](`crate::binary_benchmark_group`) only: This struct mirrors the `#[bench]` and
/// `#[benches]` attribute of a [`crate::binary_benchmark`]
#[derive(Debug, Clone, PartialEq)]
pub struct Bench {
/// The [`BenchmarkId`] used to uniquely identify this benchmark within a [`BinaryBenchmark`]
pub id: BenchmarkId,
/// All [`Command`]s
pub commands: Vec<Command>,
/// An optional [`BinaryBenchmarkConfig`]
///
/// This field stores the internal representation of the [`BinaryBenchmarkConfig`]. Use
/// `BinaryBenchmarkConfig::into` to generate the internal configuration from a
/// [`BinaryBenchmarkConfig`]
pub config: Option<internal::InternalBinaryBenchmarkConfig>,
/// The `setup` function to be executed before the [`Command`] is executed
pub setup: Option<fn()>,
/// The `teardown` function to be executed after the [`Command`] is executed
pub teardown: Option<fn()>,
}
/// [low level api](`crate::binary_benchmark_group`) only: Mirror the [`crate::binary_benchmark`]
/// attribute
///
/// A `BinaryBenchmark` can be created in two ways. Either with [`BinaryBenchmark::new`]. Or via the
/// [`crate::binary_benchmark_attribute`] macro used with a function annotated with the
/// [`crate::binary_benchmark`] attribute. So, you can start with the high-level api using the
/// attribute and then go on in the low-level api.
///
/// # Examples
///
/// For examples using [`BinaryBenchmark::new`], see there. Here's an example using the
/// [`crate::binary_benchmark_attribute`]
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{
/// binary_benchmark, binary_benchmark_group, binary_benchmark_attribute, Bench
/// };
///
/// #[binary_benchmark]
/// #[bench::foo("foo")]
/// fn bench_binary(arg: &str) -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-foo"))
/// .arg(arg)
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = |group: &mut BinaryBenchmarkGroup| {
/// let mut binary_benchmark = binary_benchmark_attribute!(bench_binary);
///
/// // Continue and add another `Bench` to the `BinaryBenchmark`
/// binary_benchmark.bench(Bench::new("bar")
/// .command(iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-foo"))
/// .arg("bar")
/// )
/// );
///
/// // Finally, add the `BinaryBenchmark` to the group
/// group
/// .binary_benchmark(binary_benchmark);
/// }
/// );
/// # fn main() {}
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct BinaryBenchmark {
/// An id which has to be unique within the same [`BinaryBenchmarkGroup`]
///
/// In the high-level api this is the name of the function which is annotated by
/// [`crate::binary_benchmark`]
pub id: BenchmarkId,
/// An optional [`BinaryBenchmarkConfig`] which is applied to all [`Command`]s within this
/// [`BinaryBenchmark`]
pub config: Option<internal::InternalBinaryBenchmarkConfig>,
/// All [`Bench`]es which were added to this [`BinaryBenchmark`]
pub benches: Vec<Bench>,
/// The default `setup` function for all [`Bench`]es within this [`BinaryBenchmark`]. It can be
/// overwritten in a [`Bench`]
pub setup: Option<fn()>,
/// The default `teardown` function for all [`Bench`]es within this [`BinaryBenchmark`]. It can
/// be overwritten in a [`Bench`]
pub teardown: Option<fn()>,
}
/// Provide the [`Command`] to be benchmarked
///
/// `Command` is a builder for the binary which is going to be benchmarked providing fine-grained
/// control over how the `Command` for the valgrind benchmark should be executed.
///
/// The default configuration is created with [`Command::new`] providing a path to an executable.
/// Adding a crate's binary is usually done with `env!("CARGO_BIN_EXE_<name>")` where `<name>` is
/// the name of the binary. The builder methods allow the configuration to be changed prior to
/// [`Command::build`]. The [`Command`] can be reused to build multiple processes.
///
/// # Examples
///
/// Suppose your crate's binary is called `my-echo`:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::Command;
/// let command = Command::new(env!("CARGO_BIN_EXE_my-echo"));
/// ```
///
/// However, an iai-callgrind benchmark is not limited to a crate's binaries, it can be any
/// executable in the `$PATH`, or an absolute path to a binary installed on your system. The
/// following will create a `Command` for the system's `echo` from the `$PATH`:
///
/// ```rust
/// use iai_callgrind::Command;
/// let command = Command::new("echo");
/// ```
#[derive(Debug, Default, Clone, PartialEq, IntoInner, AsRef)]
pub struct Command(internal::InternalCommand);
/// Provide the [`crate::Delay`] to specify the event for [`crate::Command`] execution start.
///
/// The default configuration is created with [`Delay::new`] providing a [`crate::DelayKind`] to
/// specify the event type and parameters for the `Delay`.
///
/// Additionally, the `Delay` can be created using `from*()` methods.
/// - [`Delay::from(duration)`](Delay::from)
/// - [`Delay::from_tcp_socket(addr)`](Delay::from_tcp_socket)
/// - [`Delay::from_udp_request(addr, request)`](Delay::from_udp_request)
/// - [`Delay::from_path(path)`](Delay::from_path)
///
/// # Examples
///
/// Suppose your command needs to start 60 seconds after the benchmark started:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use std::time::Duration;
///
/// use iai_callgrind::{Command, Delay, DelayKind};
///
/// let command = Command::new(env!("CARGO_BIN_EXE_my-echo")).delay(Delay::new(
/// DelayKind::DurationElapse(Duration::from_secs(60)),
/// ));
///
/// let command_from =
/// Command::new(env!("CARGO_BIN_EXE_my-echo")).delay(Delay::from(Duration::from_secs(60)));
///
/// let command_duration =
/// Command::new(env!("CARGO_BIN_EXE_my-echo")).delay(Duration::from_secs(60));
/// ```
///
/// However, an iai-callgrind [`Delay`] is not limited to a duration, it can be any
/// path creation event, a successful TCP connect or as well a received UDP response.
///
/// ```rust
/// use iai_callgrind::{Command, Delay, DelayKind};
///
/// let command = Command::new("echo").delay(Delay::new(DelayKind::PathExists(
/// "/your/path/to/wait/for".into(),
/// )));
///
/// let command_from = Command::new("echo").delay(Delay::from_path("/your/path/to/wait/for"));
/// ```
///
/// ```rust
/// use std::net::SocketAddr;
/// use std::time::Duration;
///
/// use iai_callgrind::{Command, Delay, DelayKind};
///
/// let command = Command::new("echo").delay(
/// Delay::new(DelayKind::TcpConnect(
/// "127.0.0.1:31000".parse::<SocketAddr>().unwrap(),
/// ))
/// .timeout(Duration::from_secs(3))
/// .poll(Duration::from_millis(50)),
/// );
///
/// let command_from = Command::new("echo").delay(
/// Delay::from_tcp_socket("127.0.0.1:31000".parse::<SocketAddr>().unwrap())
/// .timeout(Duration::from_secs(3))
/// .poll(Duration::from_millis(50)),
/// );
/// ```
///
/// ```rust
/// use std::net::SocketAddr;
/// use std::time::Duration;
///
/// use iai_callgrind::{Command, Delay, DelayKind};
///
/// let command = Command::new("echo").delay(
/// Delay::new(DelayKind::UdpResponse(
/// "127.0.0.1:34000".parse::<SocketAddr>().unwrap(),
/// vec![1],
/// ))
/// .timeout(Duration::from_secs(3))
/// .poll(Duration::from_millis(50)),
/// );
///
/// let command_from = Command::new("echo").delay(
/// Delay::from_udp_request("127.0.0.1:34000".parse::<SocketAddr>().unwrap(), vec![1])
/// .timeout(Duration::from_secs(3))
/// .poll(Duration::from_millis(50)),
/// );
/// ```
#[derive(Debug, Default, Clone, PartialEq, IntoInner, AsRef)]
pub struct Delay(internal::InternalDelay);
/// 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};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |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, Copy)]
pub enum ExitWith {
/// Exit with success is similar to `ExitCode(0)`
Success,
/// Exit with failure is similar to setting the `ExitCode` to something different from `0`
/// without having to rely on a specific exit code
Failure,
/// The exact `ExitCode` of the benchmark run
Code(i32),
}
/// The `Sandbox` in which the `setup`, `teardown` and the [`Command`] are run
///
/// The `Sandbox` is a temporary directory which is created before the execution of the
/// [`setup`](`crate::binary_benchmark`) and deleted after the
/// [`teardown`](`crate::binary_benchmark`). `setup`, the [`Command`] and `teardown` are executed
/// inside this temporary directory.
///
/// # Background and reasons for using a `Sandbox`
///
/// A [`Sandbox`] can help mitigating differences in benchmark results on different machines. As
/// long as `$TMP_DIR` is unset or set to `/tmp`, the temporary directory has a constant length on
/// unix machines (except android which uses `/data/local/tmp`). The directory itself
/// is created with a constant length but random name like `/tmp/.a23sr8fk`. It is not implausible
/// that an executable has different event counts just because the directory it is executed in has a
/// different length. For example, if a member of your project has set up the project in
/// `/home/bob/workspace/our-project` running the benchmarks in this directory, and the ci runs the
/// benchmarks in `/runner/our-project`, the event counts might differ. If possible, the benchmarks
/// should be run in an as constant as possible environment. Clearing the environment variables is
/// also such a counter-measure.
///
/// Other reasons for using a `Sandbox` are convenience, such as if you're creating files during
/// `setup` and the [`Command`] run and don't want to delete all the files manually. Or, more
/// importantly, if the [`Command`] is destructive and deletes files, it is usually safer to execute
/// such a [`Command`] in a temporary directory where it cannot do any harm to your or others file
/// systems during the benchmark runs.
///
/// # Sandbox cleanup
///
/// The changes the `setup` makes in this directory persist until the `teardown` has finished. So,
/// the [`Command`] can for example pick up any files created by the `setup` method. If run in a
/// `Sandbox`, the `teardown` usually doesn't have to delete any files, because the whole
/// directory is deleted after its usage. There is an exception to the rule. If any of the files
/// inside the directory is not removable, for example because the permissions of a file don't allow
/// the file to be deleted, then the whole directory persists. You can use the `teardown` to reset
/// all permission bits to be readable and writable, so the cleanup can succeed.
///
/// To simply copy fixtures or whole directories into the `Sandbox` use [`Sandbox::fixtures`].
#[derive(Debug, Clone, IntoInner, AsRef)]
pub struct Sandbox(internal::InternalSandbox);
impl Bench {
/// Create a new `Bench` with a unique [`BenchmarkId`]
///
/// If the provided [`BenchmarkId`] is invalid, `iai-callgrind` exits with an error.
///
/// # Scope of uniqueness of the [`BenchmarkId`]
///
/// The id needs to be unique within the same [`BinaryBenchmark`]
///
/// # Examples
///
/// The [`BenchmarkId`] can be created from any &str-like
///
/// ```
/// use iai_callgrind::Bench;
///
/// let bench = Bench::new("my_unique_id");
/// ```
///
/// but you can also provide the [`BenchmarkId`]
///
/// ```
/// use iai_callgrind::{Bench, BenchmarkId};
///
/// let bench = Bench::new(BenchmarkId::new("my_unique_id"));
/// ```
pub fn new<T>(id: T) -> Self
where
T: Into<BenchmarkId>,
{
Self {
id: id.into(),
config: None,
commands: vec![],
setup: None,
teardown: None,
}
}
/// Add a [`BinaryBenchmarkConfig`] for this `Bench`
///
/// A `Bench` without a `BinaryBenchmarkConfig` behaves like having specified the default
/// [`BinaryBenchmarkConfig`]. This [`BinaryBenchmarkConfig`] overwrites the values of a
/// [`BinaryBenchmarkConfig`] specified at a higher level. See there for more details.
///
/// # Examples
///
/// ```
/// use iai_callgrind::{Bench, BinaryBenchmarkConfig};
///
/// let bench = Bench::new("some_id").config(BinaryBenchmarkConfig::default().env("FOO", "BAR"));
/// ```
pub fn config<T>(&mut self, config: T) -> &mut Self
where
T: Into<internal::InternalBinaryBenchmarkConfig>,
{
self.config = Some(config.into());
self
}
/// Add a [`Command`] to this `Bench`
///
/// A `Bench` with multiple `Commands` behaves exactly as the
/// [`#[benches]`](crate::binary_benchmark) attribute
///
/// # Errors
///
/// It is an error if a `Bench` does not contain any `Commands`, so this method or
/// [`Bench::commands`] has to be called at least once.
///
/// # Examples
///
/// Suppose the crate's binary is called `my-echo`:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{Bench, Command};
///
/// let bench = Bench::new("some_id")
/// .command(Command::new(env!("CARGO_BIN_EXE_my-echo")))
/// .clone();
///
/// assert_eq!(bench.commands.len(), 1);
/// ```
pub fn command<T>(&mut self, command: T) -> &mut Self
where
T: Into<Command>,
{
self.commands.push(command.into());
self
}
/// Add multiple [`Command`]s to this `Bench`
///
/// See also [`Bench::command`].
///
/// # Examples
///
/// Suppose the crate's binary is called `my-echo`
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{Bench, Command};
///
/// let mut command = Command::new(env!("CARGO_BIN_EXE_my-echo"));
///
/// let echo_foo = command.clone().arg("foo").build();
/// let echo_bar = command.arg("bar").build();
///
/// let mut bench = Bench::new("some_id");
/// bench.commands([echo_foo, echo_bar]).clone();
///
/// assert_eq!(bench.commands.len(), 2);
/// ```
pub fn commands<I, T>(&mut self, commands: T) -> &mut Self
where
I: Into<Command>,
T: IntoIterator<Item = I>,
{
self.commands.extend(commands.into_iter().map(Into::into));
self
}
/// Add a `setup` function to be executed before the [`Command`] is executed
///
/// This `setup` function overwrites the `setup` function of [`BinaryBenchmark`]. In the
/// presence of a [`Sandbox`], this function is executed in the sandbox.
///
/// # Examples
///
/// ```rust
/// use iai_callgrind::Bench;
///
/// fn my_setup() {
/// println!("Place everything in this function you want to be executed prior to the Command");
/// }
///
/// let mut bench = Bench::new("some_id");
/// bench.setup(my_setup);
///
/// assert!(bench.setup.is_some())
/// ```
///
/// Overwrite the setup function from a [`BinaryBenchmark`]
///
/// ```rust
/// use iai_callgrind::{Bench, BinaryBenchmark};
/// fn binary_benchmark_setup() {
/// println!("setup in BinaryBenchmark")
/// }
///
/// fn bench_setup() {
/// println!("setup in Bench")
/// }
///
/// BinaryBenchmark::new("bench_binary")
/// .setup(binary_benchmark_setup)
/// .bench(Bench::new("some_id").setup(bench_setup));
/// ```
pub fn setup(&mut self, setup: fn()) -> &mut Self {
self.setup = Some(setup);
self
}
/// Add a `teardown` function to be executed after the [`Command`] is executed
///
/// This `teardown` function overwrites the `teardown` function of [`BinaryBenchmark`]. In the
/// presence of a [`Sandbox`], this function is executed in the sandbox.
///
/// # Examples
///
/// ```rust
/// use iai_callgrind::Bench;
///
/// fn my_teardown() {
/// println!(
/// "Place everything in this function you want to be executed after the execution of the \
/// Command"
/// );
/// }
///
/// let mut bench = Bench::new("some_id");
/// bench.teardown(my_teardown);
///
/// assert!(bench.teardown.is_some())
/// ```
///
/// Overwrite the teardown function from a [`BinaryBenchmark`]
///
/// ```rust
/// use iai_callgrind::{Bench, BinaryBenchmark};
/// fn binary_benchmark_teardown() {
/// println!("teardown in BinaryBenchmark")
/// }
///
/// fn bench_teardown() {
/// println!("teardown in Bench")
/// }
///
/// BinaryBenchmark::new("bench_binary")
/// .teardown(binary_benchmark_teardown)
/// .bench(Bench::new("some_id").teardown(bench_teardown));
/// ```
pub fn teardown(&mut self, teardown: fn()) -> &mut Self {
self.teardown = Some(teardown);
self
}
/// Add each line of a file as [`Command`] to this [`Bench`] using a `generator` function.
///
/// This method mirrors the `file` parameter of the `#[benches]` attribute as far as possible.
/// In the low-level api you can achieve the same or more quickly yourself and this method
/// exists for the sake of completeness (and convenience).
///
/// The file has to exist at the time you're using this method and the file has to be encoded in
/// UTF-8. The `generator` function tells us how to convert each line of the file into a
/// [`Command`].
///
/// # Notable differences to high-level api
///
/// If the file path in the high-level api is relative we interpret the path relative to the
/// workspace root (and make it absolute). In this method we use the path AS IS.
///
/// # Errors
///
/// If the file is empty, cannot be opened for reading or a line in the file cannot be converted
/// to a String. Also, the error from the `generator` is propagated. The errors containing the
/// line number use a 0-indexed line number.
///
/// # Examples
///
/// Suppose your cargo's binary is named `my-echo` and you want to convert a file with inputs
/// `benches/inputs` into commands and each line is the only argument for your `my-echo` binary:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{binary_benchmark_group, BinaryBenchmark, Bench};
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = |group: &mut BinaryBenchmarkGroup| {
/// group.binary_benchmark(BinaryBenchmark::new("some_id")
/// .bench(Bench::new("bench_id")
/// .file("benches/inputs", |line| {
/// Ok(iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-echo"))
/// .arg(line)
/// .build())
/// }).unwrap()
/// )
/// )
/// }
/// );
/// # fn main() {}
/// ```
pub fn file<T>(
&mut self,
path: T,
generator: fn(String) -> Result<Command, String>,
) -> Result<&mut Self, String>
where
T: AsRef<Path>,
{
let path = path.as_ref();
let file = File::open(path).map_err(|error| {
format!(
"{}: Error opening file '{}': {error}",
self.id,
path.display(),
)
})?;
let reader = BufReader::new(file);
let mut has_lines = false;
for (index, line) in reader.lines().enumerate() {
has_lines = true;
let line = line.map_err(|error| {
format!(
"{}: Error reading line {index} in file '{}': {error}",
self.id,
path.display()
)
})?;
let command = generator(line).map_err(|error| {
format!(
"{}: Error generating command from line {index} in file '{}': {error}",
self.id,
path.display()
)
})?;
self.commands.push(command);
}
if !has_lines {
return Err(format!("{}: Empty file '{}'", self.id, path.display()));
}
Ok(self)
}
}
impl From<&mut Bench> for Bench {
fn from(value: &mut Bench) -> Self {
value.clone()
}
}
impl From<&Bench> for Bench {
fn from(value: &Bench) -> Self {
value.clone()
}
}
impl BenchmarkId {
/// Convenience method to create a `BenchmarkId` with a parameter in the [low level
/// api](crate::binary_benchmark_group)
///
/// The `parameter` is simply appended to the `id` with an underscore, so
/// `BenchmarkId::with_parameter("some", 1)` is equivalent to `BenchmarkId::new("some_1")`
///
/// # Examples
///
/// ```
/// use iai_callgrind::BenchmarkId;
///
/// let new_id = BenchmarkId::new("prefix_1");
/// let with_parameter = BenchmarkId::with_parameter("prefix", 1);
/// assert_eq!(new_id, with_parameter);
/// ```
///
/// ```rust
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group,BenchmarkId, BinaryBenchmark, Bench, Command};
/// use std::ffi::OsStr;
///
/// binary_benchmark_group!(
/// name = low_level_group;
/// benchmarks = |group: &mut BinaryBenchmarkGroup| {
/// let mut binary_benchmark = BinaryBenchmark::new("some_id");
/// for arg in 0..10 {
/// let id = BenchmarkId::with_parameter("prefix", arg);
/// binary_benchmark.bench(
/// Bench::new(id)
/// .command(
/// Command::new("echo").arg(arg.to_string()).build()
/// )
/// );
/// }
/// group.binary_benchmark(binary_benchmark);
/// }
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = low_level_group);
/// # }
/// ```
pub fn with_parameter<T, P>(id: T, parameter: P) -> Self
where
T: AsRef<str>,
P: Display,
{
Self(format!("{}_{parameter}", id.as_ref()))
}
/// Create a new `BenchmarkId`
///
/// `BenchmarkId`s can be created from any string-like input. See [`BenchmarkId::validate`] for
/// ids which are considered valid.
///
/// # Examples
///
/// ```rust
/// use iai_callgrind::BenchmarkId;
///
/// let id = BenchmarkId::new("my_id");
///
/// assert!(id.validate().is_ok());
/// ```
pub fn new<T>(id: T) -> Self
where
T: Into<String>,
{
Self(id.into())
}
/// Returns ok if this [`BenchmarkId`] is valid
///
/// An id should be short, descriptive besides being unique. The requirements for the uniqueness
/// differ for the structs where a `BenchmarkId` is used and is further described there.
///
/// We use a minimal subset of rust's identifiers. A valid `BenchmarkId` starts with an ascii
/// alphabetic letter `[a-zA-Z]` or underscore `[_]`. All following characters can be an ascii
/// alphabetic letter, underscore or a digit `[0-9]`. At least one valid character must be
/// present.
///
/// The `BenchmarkId` is used by `iai-callgrind` as file and directory name for the output files
/// of the benchmarks. Therefore, the limit for an id is chosen to be 120 bytes. This is a
/// calculation with some headroom. There are file systems which do not even allow 255 bytes. If
/// you're working on such a peculiar file system, you have to restrict your ids to even fewer
/// bytes which is `floor(MAX_LENGTH/2) - 1`. Leaving the maximum bytes aside, the best IDs are
/// simple, short and descriptive.
///
/// Usually, it is not necessary to call this function, since we already check the validity of
/// benchmark ids prior to the execution of the benchmark runner. But if your ids come from an
/// untrusted source you can use this method for more immediate feedback.
///
/// # Errors
///
/// This function will return an error describing the source of the error if the id is invalid
///
/// # Examples
///
/// ```rust
/// use iai_callgrind::BenchmarkId;
///
/// assert!(BenchmarkId::new("").validate().is_err());
/// assert!(BenchmarkId::new("0a").validate().is_err());
/// assert!(BenchmarkId::new("id with spaces").validate().is_err());
/// assert!(BenchmarkId::new("path/to").validate().is_err());
/// assert!(BenchmarkId::new("no::module::too").validate().is_err());
///
/// assert!(BenchmarkId::new("_").validate().is_ok());
/// assert!(BenchmarkId::new("abc").validate().is_ok());
/// assert!(BenchmarkId::new("a9").validate().is_ok());
/// assert!(BenchmarkId::new("z_").validate().is_ok());
/// assert!(BenchmarkId::new("some_id").validate().is_ok());
/// ```
#[allow(clippy::missing_panics_doc)]
pub fn validate(&self) -> Result<(), String> {
const MAX_LENGTH_ID: usize = 255;
if self.0.is_empty() {
return Err("Invalid id: Cannot be empty".to_owned());
}
let mut bytes = self.0.bytes();
// This unwrap is safe, since we just checked that the string is not empty
let first = bytes.next().unwrap();
if first.is_ascii_alphabetic() || first == b'_' {
for (index, byte) in (1..).zip(bytes) {
if index > MAX_LENGTH_ID {
return Err(format!(
"Invalid id '{}': Maximum length of {MAX_LENGTH_ID} bytes reached",
&self.0,
));
}
if byte.is_ascii() {
if !(byte.is_ascii_alphanumeric() || byte == b'_') {
return Err(format!(
"Invalid id '{}' at position {index}: Invalid character '{}'",
&self.0,
char::from(byte)
));
}
} else {
return Err(format!(
"Invalid id '{}' at position {index}: Encountered non-ascii character",
&self.0
));
}
}
} else if first.is_ascii() {
return Err(format!(
"Invalid id '{}': As first character is '{}' not allowed",
&self.0,
char::from(first)
));
} else {
return Err(format!(
"Invalid id '{}': Encountered non-ascii character as first character",
&self.0
));
}
Ok(())
}
}
impl Display for BenchmarkId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl From<BenchmarkId> for String {
fn from(value: BenchmarkId) -> Self {
value.0
}
}
impl<T> From<T> for BenchmarkId
where
T: AsRef<str>,
{
fn from(value: T) -> Self {
Self(value.as_ref().to_owned())
}
}
impl BinaryBenchmark {
/// Create a new `BinaryBenchmark`
///
/// A `BinaryBenchmark` is the equivalent of the
/// [`#[binary_benchmark]`](`crate::binary_benchmark`) attribute in the low-level api and needs
/// a [`BenchmarkId`]. In the high-level api the id is derived from the function name.
///
/// The [`BenchmarkId`] is used together with the id of each [`Bench`] to create a directory
/// name. This usually limits the combined length of the ids to `255 - 1` but can be less
/// depending on the file system. See [`BenchmarkId`] for more details
///
/// # Scope of uniqueness of the [`BenchmarkId`]
///
/// The id needs to be unique within the same [`crate::binary_benchmark_group`]. It is
/// recommended to use an id which is unique within the whole benchmark file, although doing
/// otherwise does currently not incur any negative consequence.
///
/// # Examples
///
/// ```rust
/// use iai_callgrind::{BenchmarkId, BinaryBenchmark};
///
/// let binary_benchmark = BinaryBenchmark::new("some_id");
/// assert_eq!(binary_benchmark.id, BenchmarkId::new("some_id"));
/// ```
pub fn new<T>(id: T) -> Self
where
T: Into<BenchmarkId>,
{
Self {
id: id.into(),
config: None,
benches: vec![],
setup: None,
teardown: None,
}
}
/// Add a [`BinaryBenchmarkConfig`] to this `BinaryBenchmark`
///
/// # Examples
///
/// ```rust
/// use iai_callgrind::{BinaryBenchmark, BinaryBenchmarkConfig};
///
/// let binary_benchmark = BinaryBenchmark::new("some_id")
/// .config(BinaryBenchmarkConfig::default().env("FOO", "BAR"))
/// .clone();
///
/// assert_eq!(
/// binary_benchmark.config,
/// Some(BinaryBenchmarkConfig::default().env("FOO", "BAR").into())
/// );
/// ```
pub fn config<T>(&mut self, config: T) -> &mut Self
where
T: Into<internal::InternalBinaryBenchmarkConfig>,
{
self.config = Some(config.into());
self
}
/// Add a [`Bench`] to this `BinaryBenchmark`
///
/// Adding a [`Bench`] which doesn't contain a [`Command`] is an error.
///
/// # Examples
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{Bench, BinaryBenchmark, Command};
///
/// // Each `Bench` needs at least one `Command`!
/// let mut bench = Bench::new("some_id");
/// bench.command(Command::new(env!("CARGO_BIN_EXE_my-echo")));
///
/// let binary_benchmark = BinaryBenchmark::new("bench_binary")
/// .bench(bench.clone())
/// .clone();
///
/// assert_eq!(binary_benchmark.benches[0], bench);
/// ```
pub fn bench<T>(&mut self, bench: T) -> &mut Self
where
T: Into<Bench>,
{
self.benches.push(bench.into());
self
}
/// Add a `setup` function to this `BinaryBenchmark`
///
/// This `setup` function is used in all [`Bench`]es of this `BinaryBenchmark` if not overridden
/// by the `Bench`.
///
/// # Examples
///
/// ```rust
/// use iai_callgrind::Bench;
/// fn my_setup() {
/// println!(
/// "Place everything in this function you want to be executed before the execution of \
/// the Command"
/// );
/// }
///
/// let bench = Bench::new("some_id").setup(my_setup).clone();
///
/// assert!(bench.setup.is_some())
/// ```
///
/// Overwrite the setup function from this `BinaryBenchmark` in a [`Bench`]
///
/// ```rust
/// use iai_callgrind::{Bench, BinaryBenchmark};
/// fn binary_benchmark_setup() {
/// println!("setup in BinaryBenchmark")
/// }
///
/// fn bench_setup() {
/// println!("setup in Bench")
/// }
///
/// BinaryBenchmark::new("bench_binary")
/// .setup(binary_benchmark_setup)
/// .bench(Bench::new("some_id").setup(bench_setup));
/// ```
pub fn setup(&mut self, setup: fn()) -> &mut Self {
self.setup = Some(setup);
self
}
/// Add a `teardown` function to this `BinaryBenchmark`
///
/// This `teardown` function is used in all [`Bench`]es of this `BinaryBenchmark` if not
/// overridden by the `Bench`.
///
/// # Examples
///
/// ```rust
/// use iai_callgrind::Bench;
/// fn my_teardown() {
/// println!(
/// "Place everything in this function you want to be executed after the execution of the \
/// Command"
/// );
/// }
///
/// let bench = Bench::new("some_id").teardown(my_teardown).clone();
///
/// assert!(bench.teardown.is_some())
/// ```
///
/// Overwrite the teardown function from this `BinaryBenchmark` in a [`Bench`]
///
/// ```rust
/// use iai_callgrind::{Bench, BinaryBenchmark};
/// fn binary_benchmark_teardown() {
/// println!("teardown in BinaryBenchmark")
/// }
///
/// fn bench_teardown() {
/// println!("teardown in Bench")
/// }
///
/// BinaryBenchmark::new("bench_binary")
/// .teardown(binary_benchmark_teardown)
/// .bench(Bench::new("some_id").teardown(bench_teardown));
/// ```
pub fn teardown(&mut self, teardown: fn()) -> &mut Self {
self.teardown = Some(teardown);
self
}
}
impl From<&mut BinaryBenchmark> for BinaryBenchmark {
fn from(value: &mut BinaryBenchmark) -> Self {
value.clone()
}
}
impl From<&BinaryBenchmark> for BinaryBenchmark {
fn from(value: &BinaryBenchmark) -> Self {
value.clone()
}
}
impl BinaryBenchmarkConfig {
/// 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;
///
/// BinaryBenchmarkConfig::default()
/// .callgrind_args(["collect-atstart=no", "toggle-collect=some::path"]);
/// ```
#[deprecated = "Please use callgrind_args instead"]
pub fn raw_callgrind_args<I, T>(&mut self, args: T) -> &mut Self
where
I: AsRef<str>,
T: IntoIterator<Item = I>,
{
self.0.callgrind_args.extend_ignore_flag(args);
self
}
/// Create a new `BinaryBenchmarkConfig` with initial callgrind arguments
///
/// See also [`BinaryBenchmarkConfig::callgrind_args`].
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark, binary_benchmark_group};
/// # #[binary_benchmark]
/// # fn some_func() -> iai_callgrind::Command { iai_callgrind::Command::new("/some/path") }
/// # binary_benchmark_group!(name = some_group; benchmarks = some_func);
/// # fn main() {
/// use iai_callgrind::{BinaryBenchmarkConfig, main};
///
/// main!(
/// config =
/// BinaryBenchmarkConfig::with_callgrind_args(["toggle-collect=something"]);
/// binary_benchmark_groups = some_group
/// );
/// # }
/// ```
pub fn with_callgrind_args<I, T>(args: T) -> Self
where
I: AsRef<str>,
T: IntoIterator<Item = I>,
{
Self(internal::InternalBinaryBenchmarkConfig {
callgrind_args: RawArgs::from_iter(args),
..Default::default()
})
}
/// 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;
///
/// BinaryBenchmarkConfig::default()
/// .callgrind_args(["collect-atstart=no", "toggle-collect=some::path"]);
/// ```
pub fn callgrind_args<I, T>(&mut self, args: T) -> &mut Self
where
I: AsRef<str>,
T: IntoIterator<Item = I>,
{
self.0.callgrind_args.extend_ignore_flag(args);
self
}
/// Pass valgrind arguments to all tools
///
/// Only core [valgrind
/// arguments](https://valgrind.org/docs/manual/manual-core.html#manual-core.options) are
/// allowed.
///
/// These arguments can be overwritten by tool specific arguments for example with
/// [`BinaryBenchmarkConfig::callgrind_args`] or [`crate::Tool::args`].
///
/// # Examples
///
/// Specify `--trace-children=no` for all configured tools (including callgrind):
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig, Tool, ValgrindTool};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default()
/// .valgrind_args(["--trace-children=no"])
/// .tool(Tool::new(ValgrindTool::DHAT));
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
///
/// Overwrite the valgrind argument `--num-callers=25` for `DHAT` with `--num-callers=30`:
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig, Tool, ValgrindTool};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default()
/// .valgrind_args(["--num-callers=25"])
/// .tool(Tool::new(ValgrindTool::DHAT)
/// .args(["--num-callers=30"])
/// );
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn valgrind_args<I, T>(&mut self, args: T) -> &mut Self
where
I: AsRef<str>,
T: IntoIterator<Item = I>,
{
self.0.valgrind_args.extend_ignore_flag(args);
self
}
/// Add an environment variable to the [`Command`]
///
/// 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};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_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 variables to the [`Command`]
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_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 binary 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};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_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 [`crate::BinaryBenchmarkConfig::pass_through_env`].
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::binary_benchmark_group;
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_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};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_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 directory which `cargo
/// bench` sets. 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};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_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};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig, Sandbox};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default()
/// .sandbox(Sandbox::new(true))
/// .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 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};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_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};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_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 [`crate::FlamegraphConfig`]
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_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_config = Some(config.into());
self
}
/// Enable performance regression checks with a [`crate::RegressionConfig`]
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig, RegressionConfig};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().regression(RegressionConfig::default());
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn regression<T>(&mut self, config: T) -> &mut Self
where
T: Into<internal::InternalRegressionConfig>,
{
self.0.regression_config = Some(config.into());
self
}
/// Add a configuration to run a valgrind [`crate::Tool`] in addition to callgrind
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig, Tool, ValgrindTool};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default()
/// .tool(
/// Tool::new(ValgrindTool::DHAT)
/// );
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn tool<T>(&mut self, tool: T) -> &mut Self
where
T: Into<internal::InternalTool>,
{
self.0.tools.update(tool.into());
self
}
/// Add multiple configurations to run valgrind [`crate::Tool`]s in addition to callgrind
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::{binary_benchmark_group};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig, Tool, ValgrindTool};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default()
/// .tools(
/// [
/// Tool::new(ValgrindTool::DHAT),
/// Tool::new(ValgrindTool::Massif)
/// ]
/// );
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn tools<I, T>(&mut self, tools: T) -> &mut Self
where
I: Into<internal::InternalTool>,
T: IntoIterator<Item = I>,
{
self.0.tools.update_all(tools.into_iter().map(Into::into));
self
}
/// Override previously defined configurations of valgrind [`crate::Tool`]s
///
/// See also [`crate::LibraryBenchmarkConfig::tool_override`] for more details.
///
/// # Example
///
/// The following will run `DHAT` and `Massif` (and the default callgrind) for all benchmarks in
/// `main!` besides for `foo` which will just run `Memcheck` (and callgrind).
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{
/// binary_benchmark, binary_benchmark_group, BinaryBenchmarkConfig, main, Tool,
/// ValgrindTool
/// };
///
/// #[binary_benchmark]
/// #[bench::some(
/// config = BinaryBenchmarkConfig::default()
/// .tool_override(Tool::new(ValgrindTool::Memcheck))
/// )]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default()
/// .tools(
/// [
/// Tool::new(ValgrindTool::DHAT),
/// Tool::new(ValgrindTool::Massif)
/// ]
/// );
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn tool_override<T>(&mut self, tool: T) -> &mut Self
where
T: Into<internal::InternalTool>,
{
self.0
.tools_override
.get_or_insert(internal::InternalTools::default())
.update(tool.into());
self
}
/// Override previously defined configurations of valgrind [`crate::Tool`]s
///
/// See also [`crate::LibraryBenchmarkConfig::tool_override`] for more details.
///
/// # Example
///
/// The following will run `DHAT` (and the default callgrind) for all benchmarks in
/// `main!` besides for `foo` which will run `Massif` and `Memcheck` (and callgrind).
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{
/// binary_benchmark, binary_benchmark_group, BinaryBenchmarkConfig, main, Tool,
/// ValgrindTool
/// };
///
/// #[binary_benchmark]
/// #[bench::some(
/// config = BinaryBenchmarkConfig::default()
/// .tools_override([
/// Tool::new(ValgrindTool::Massif),
/// Tool::new(ValgrindTool::Memcheck),
/// ])
/// )]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default()
/// .tool(
/// Tool::new(ValgrindTool::DHAT),
/// );
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn tools_override<I, T>(&mut self, tools: T) -> &mut Self
where
I: Into<internal::InternalTool>,
T: IntoIterator<Item = I>,
{
self.0
.tools_override
.get_or_insert(internal::InternalTools::default())
.update_all(tools.into_iter().map(Into::into));
self
}
/// Configure benchmarks to run in a [`Sandbox`] (Default: false)
///
/// If specified, we create a temporary directory in which the `setup` and `teardown` functions
/// of the `#[binary_benchmark]` (`#[bench]`, `#[benches]`) and the [`Command`] itself are run.
///
/// A good 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};
/// # binary_benchmark_group!(
/// # name = my_group;
/// # benchmarks = |_group: &mut BinaryBenchmarkGroup| {});
/// use iai_callgrind::{main, BinaryBenchmarkConfig, Sandbox};
///
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().sandbox(Sandbox::new(true));
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn sandbox<T>(&mut self, sandbox: T) -> &mut Self
where
T: Into<internal::InternalSandbox>,
{
self.0.sandbox = Some(sandbox.into());
self
}
/// Configure the [`crate::OutputFormat`] of the terminal output of Iai-Callgrind
///
/// # Examples
///
/// ```rust
/// use iai_callgrind::{main, BinaryBenchmarkConfig, OutputFormat};
/// # use iai_callgrind::{binary_benchmark, binary_benchmark_group};
/// # #[binary_benchmark]
/// # fn some_func() -> iai_callgrind::Command { iai_callgrind::Command::new("some/path") }
/// # binary_benchmark_group!(
/// # name = some_group;
/// # benchmarks = some_func
/// # );
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default()
/// .output_format(OutputFormat::default()
/// .truncate_description(Some(200))
/// );
/// binary_benchmark_groups = some_group
/// );
/// # }
pub fn output_format<T>(&mut self, output_format: T) -> &mut Self
where
T: Into<internal::InternalOutputFormat>,
{
self.0.output_format = Some(output_format.into());
self
}
/// Execute the `setup` in parallel to the [`Command`].
///
/// See also [`Command::setup_parallel`]
///
/// # Examples
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use std::time::Duration;
/// use std::net::{SocketAddr, TcpListener};
/// use std::thread;
/// use iai_callgrind::{
/// binary_benchmark_group, binary_benchmark, main, BinaryBenchmarkConfig, Command,
/// Delay, DelayKind
/// };
///
/// fn setup_tcp_server() {
/// thread::sleep(Duration::from_millis(300));
/// let _listener = TcpListener::bind("127.0.0.1:31000".parse::<SocketAddr>().unwrap()).unwrap();
/// thread::sleep(Duration::from_secs(1));
/// }
///
/// #[binary_benchmark]
/// #[bench::delay(
/// setup = setup_tcp_server(),
/// config = BinaryBenchmarkConfig::default()
/// .setup_parallel(true)
/// )]
/// fn bench_binary() -> iai_callgrind::Command {
/// Command::new(env!("CARGO_BIN_EXE_my-echo"))
/// .delay(
/// Delay::new(
/// DelayKind::TcpConnect("127.0.0.1:31000".parse::<SocketAddr>().unwrap()))
/// .timeout(Duration::from_millis(500))
/// ).build()
/// }
///
/// binary_benchmark_group!(name = delay; benchmarks = bench_binary);
/// # fn main() {
/// main!(binary_benchmark_groups = delay);
/// # }
/// ```
pub fn setup_parallel(&mut self, setup_parallel: bool) -> &mut Self {
self.0.setup_parallel = Some(setup_parallel);
self
}
}
impl BinaryBenchmarkGroup {
/// Add a [`BinaryBenchmark`] to this group
///
/// This can be a binary benchmark created with [`BinaryBenchmark::new`] or a
/// [`crate::binary_benchmark`] attributed function addable with the
/// [`crate::binary_benchmark_attribute`] macro.
///
/// It is an error to add a [`BinaryBenchmark`] without having added a [`Bench`] to it.
///
/// # Examples
///
/// Add a [`BinaryBenchmark`] to this group
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{binary_benchmark_group, BinaryBenchmark, Bench, BinaryBenchmarkGroup};
///
/// fn setup_my_group(group: &mut BinaryBenchmarkGroup) {
/// group.binary_benchmark(BinaryBenchmark::new("bench_binary")
/// .bench(Bench::new("foo")
/// .command(iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-foo"))
/// .arg("foo")
/// )
/// )
/// );
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = |group: &mut BinaryBenchmarkGroup| setup_my_group(group)
/// );
/// # fn main() {}
/// ```
///
/// Or, add a `#[binary_benchmark]` annotated function to this group:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{binary_benchmark, binary_benchmark_group, binary_benchmark_attribute};
///
/// #[binary_benchmark]
/// #[bench::foo("foo")]
/// fn bench_binary(arg: &str) -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-foo"))
/// .arg(arg)
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = |group: &mut BinaryBenchmarkGroup| {
/// group
/// .binary_benchmark(binary_benchmark_attribute!(bench_binary))
/// }
/// );
/// # fn main() {}
/// ```
pub fn binary_benchmark<T>(&mut self, binary_benchmark: T) -> &mut Self
where
T: Into<BinaryBenchmark>,
{
self.binary_benchmarks.push(binary_benchmark.into());
self
}
/// Add multiple [`BinaryBenchmark`]s at once
pub fn binary_benchmarks<I, T>(&mut self, binary_benchmarks: T) -> &mut Self
where
I: Into<BinaryBenchmark>,
T: IntoIterator<Item = I>,
{
self.binary_benchmarks
.extend(binary_benchmarks.into_iter().map(Into::into));
self
}
}
impl Command {
/// Create a new [`Command`] which is run under valgrind.
///
/// Use
/// [`env!("CARGO_BIN_EXE_<name>)`](https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates)
/// to provide the path to an executable of your project instead of `target/release/<name>`.
///
/// This `Command` is a builder for the binary which is going to be benchmarked but is not
/// executed right away. We simply gather all the information to be finally able to execute the
/// command under valgrind, later (after we collected all the commands in this benchmark file).
/// As opposed to [`std::process::Command`], the build is finalized with [`Command::build`].
///
/// # Relative paths
///
/// Relative paths are interpreted relative to the current directory and if not running the
/// benchmarks in a [`Sandbox`], depends on where `cargo bench` sets the current directory.
/// Usually, it's best to use [`Path::canonicalize`] to resolve the relative path to a binary in
/// your project's directory. In case you're running the benchmark in a [`Sandbox`], the path is
/// interpreted relative to the root directory of the `Sandbox`. Iai-Callgrind tries to resolve
/// simple names like `Command::new("echo")` searching the `$PATH`. To disambiguate between
/// simple names and relative paths, use `./`. For example `echo` is searched in the `$PATH` and
/// `./echo` is interpreted relative.
///
/// # Examples
///
/// Assume the project's binary or one of your project's binaries name is `my-echo`:
///
/// ```
/// # macro_rules! env { ($m:tt) => {{ "/home/my_project/target/release/my-echo" }} }
/// use iai_callgrind::Command;
///
/// let command = Command::new(env!("CARGO_BIN_EXE_my-echo"));
/// ```
///
/// or use your system's echo from the `$PATH` with
///
/// ```
/// use iai_callgrind::Command;
///
/// let command = Command::new("echo").arg("foo").build();
/// ```
pub fn new<T>(path: T) -> Self
where
T: AsRef<OsStr>,
{
Self(internal::InternalCommand {
path: PathBuf::from(path.as_ref()),
..Default::default()
})
}
/// Delay the execution of the [`Command`]
///
/// This option allows to delay the [`Command`] execution till a certain event has happened.
/// Supported events are:
/// - Timer expired
/// - File path exists
/// - TCP/UDP connect succeeded
///
/// [`Delay`] can be used in combination with [`Command::setup_parallel`] to wait for an event
/// that is triggered within the `setup()` function. E.g. the setup starts a server that is
/// needed by the [`Command`].
///
/// # Examples
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark, main, Command, Delay, DelayKind};
///
/// fn start_server() {
/// // action to start the server, creates pid file
/// std::fs::File::create("/tmp/my-server.pid").unwrap();
/// }
///
/// #[binary_benchmark]
/// #[bench::server(setup = start_server)]
/// fn bench_binary() -> Command {
/// Command::new(env!("CARGO_BIN_EXE_my-echo"))
/// .setup_parallel(true)
/// .delay(Delay::new(DelayKind::PathExists("/tmp/my-server.pid".into())))
/// .build()
/// }
///
/// binary_benchmark_group!(name = my_group; benchmarks = bench_binary);
/// # fn main() {
/// main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn delay<T: Into<Delay>>(&mut self, delay: T) -> &mut Self {
self.0.delay = Some(delay.into().into());
self
}
/// Execute the `setup()` in parallel to the [`Command`].
///
/// This option changes the execution flow in a way that the [`Command`] is executed parallel
/// to the `setup` instead of waiting for the `setup` to complete.
///
/// This can be combined with the usage of [`Delay`] to further control the timing when the
/// [`Command`] is executed.
///
/// # Examples
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use std::time::Duration;
/// use std::net::{SocketAddr, TcpListener};
/// use std::thread;
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark, main, Command, Delay, DelayKind};
///
/// fn setup_tcp_server() {
/// thread::sleep(Duration::from_millis(300));
/// let _listener = TcpListener::bind("127.0.0.1:31000".parse::<SocketAddr>().unwrap()).unwrap();
/// thread::sleep(Duration::from_secs(1));
/// }
///
/// #[binary_benchmark]
/// #[bench::delay(setup = setup_tcp_server())]
/// fn bench_binary() -> iai_callgrind::Command {
/// Command::new(env!("CARGO_BIN_EXE_my-echo"))
/// .setup_parallel(true)
/// .delay(
/// Delay::new(
/// DelayKind::TcpConnect("127.0.0.1:31000".parse::<SocketAddr>().unwrap()))
/// .timeout(Duration::from_millis(500))
/// ).build()
/// }
///
/// binary_benchmark_group!(name = delay; benchmarks = bench_binary);
/// # fn main() {
/// main!(binary_benchmark_groups = delay);
/// # }
/// ```
pub fn setup_parallel(&mut self, setup_parallel: bool) -> &mut Self {
self.0.config.setup_parallel = Some(setup_parallel);
self
}
/// Adds an argument to pass to the [`Command`]
///
/// This option works exactly the same way as [`std::process::Command::arg`]. To pass multiple
/// arguments see [`Command::args`].
///
/// # Examples
///
/// ```rust
/// # use iai_callgrind::main;
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark};
///
/// #[binary_benchmark]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-echo"))
/// .arg("foo")
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn arg<T>(&mut self, arg: T) -> &mut Self
where
T: Into<OsString>,
{
self.0.args.push(arg.into());
self
}
/// Adds multiple arguments to pass to the [`Command`]
///
/// This option works exactly the same way as [`std::process::Command::args`].
///
/// # Examples
///
/// The following will execute `my-echo foo`.
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark};
///
/// #[binary_benchmark]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-echo"))
/// .arg("foo")
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn args<I, T>(&mut self, args: T) -> &mut Self
where
I: Into<OsString>,
T: IntoIterator<Item = I>,
{
self.0.args.extend(args.into_iter().map(Into::into));
self
}
/// Configuration for the process's standard input ([`Stdin`])
///
/// This method takes an [`Stdin`], [`Stdio`] and everything that implements `Into<Stdin>`. The
/// [`Stdin`] enum mirrors most of the possibilities of [`std::process::Stdio`] but also some
/// additional possibilities most notably [`Stdin::Setup`] (see there for more details).
///
/// Per default, the stdin is not inherited from the parent and any attempt by the child process
/// to read from the stdin stream will result in the stream immediately closing.
///
/// The options you might be interested in the most are [`Stdin::File`], which mirrors the
/// behaviour of [`std::process::Stdio`] if `Stdio` is a [`std::fs::File`], and
/// [`Stdin::Setup`], which is special to `iai-callgrind` and lets you pipe the output of
/// the `setup` function into the Stdin of this [`Command`]. If you need to delay the `Command`
/// when using [`Stdin::Setup`], you can do so with [`Command::delay`].
///
/// # Implementation details
///
/// As the [`Command`] itself is not executed immediately, the [`std::process::Stdio`] is not
/// created either. We only use the information from here to create the [`std::process::Stdio`]
/// later after we collected all commands. Setting the Stdin to `Inherit` is discouraged and
/// won't have the effect you might expect, since the benchmark runner (the parent) uses the
/// Stdin for its own purposes and closes it before this [`Command`] is executed.
///
/// # Examples
///
/// Pipe the content of a file (`benches/fixture.txt`) into the stdin of this [`Command`]:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark, Stdio};
///
/// #[binary_benchmark]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// .stdin(Stdio::File("benches/fixture.txt".into()))
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
///
/// Pipe the Stdout of setup into the Stdin of this [`Command`]:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark, Stdin, Pipe};
///
/// fn setup_pipe() {
/// // All output to Stdout of this function will be piped into the Stdin of `my-exe`
/// println!("This string will be piped into the stdin of my-exe");
/// }
///
/// #[binary_benchmark(setup = setup_pipe())]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// .stdin(Stdin::Setup(Pipe::Stdout))
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
pub fn stdin<T>(&mut self, stdin: T) -> &mut Self
where
T: Into<Stdin>,
{
self.0.stdin = Some(stdin.into());
self
}
/// Configuration for the [`Command`]s standard output (Stdout) handle.
///
/// The output of benchmark commands and functions are usually captured by the benchmark runner.
/// This can be changed for example with the `--nocapture` option or here. Any option specified
/// here takes precedence over the changes which `--nocapture` makes to the Stdout of the
/// command.
///
/// # Examples
///
/// To see the output of this [`Command`] regardless of `--nocapture` in the benchmark output
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark, Stdio};
///
/// #[binary_benchmark]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// .stdout(Stdio::Inherit)
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
///
/// To pipe the Stdout into a file `/tmp/benchmark.output`:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark, Stdio};
/// use std::path::PathBuf;
///
/// #[binary_benchmark]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// .stdout(Stdio::File("/tmp/benchmark.output".into()))
/// // or
/// .stdout(PathBuf::from("/tmp/benchmark.output"))
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn stdout<T>(&mut self, stdio: T) -> &mut Self
where
T: Into<Stdio>,
{
self.0.stdout = Some(stdio.into());
self
}
/// Configuration for the [`Command`]s standard error output (Stderr) handle.
///
/// This option is similar to [`Command::stdout`] but configures the Stderr. See there for more
/// details.
///
/// # Examples
///
/// To see the error output of this [`Command`] regardless of `--nocapture` in the benchmark
/// output
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark, Stdio};
///
/// #[binary_benchmark]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// .stderr(Stdio::Inherit)
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
///
/// To pipe the Stderr into a file `/tmp/benchmark.output`:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark, Stdio};
/// use std::path::PathBuf;
///
/// #[binary_benchmark]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// .stderr(Stdio::File("/tmp/benchmark.output".into()))
/// // or
/// .stderr(PathBuf::from("/tmp/benchmark.output"))
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn stderr<T>(&mut self, stdio: T) -> &mut Self
where
T: Into<Stdio>,
{
self.0.stderr = Some(stdio.into());
self
}
/// Add an environment variable available for this [`Command`]
///
/// These environment variables are available independently of the setting of
/// [`BinaryBenchmarkConfig::env_clear`] and additive to environment variables added with
/// [`BinaryBenchmarkConfig::env`].
///
/// # Examples
///
/// An example for a custom environment variable "FOO=BAR":
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark};
///
/// #[binary_benchmark]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// .env("FOO", "BAR")
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
/// # 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 variables available for this [`Command`]
///
/// See [`Command::env`] for more details.
///
/// # Examples
///
/// Add the custom environment variables "FOO=BAR" and `BAR=BAZ`:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark};
///
/// #[binary_benchmark]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// .envs([("FOO", "BAR"), ("BAR", "BAZ")])
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Self
where
I: IntoIterator<Item = (K, V)>,
K: Into<OsString>,
V: Into<OsString>,
{
self.0
.config
.envs
.extend(vars.into_iter().map(|(k, v)| (k.into(), Some(v.into()))));
self
}
/// Set the directory of the benchmarked binary (Default: Unchanged)
///
/// See also [`BinaryBenchmarkConfig::current_dir`]
///
/// # Examples
///
/// To set the working directory of your [`Command`] to `/tmp`:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark};
///
/// #[binary_benchmark]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// .current_dir("/tmp")
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
///
/// and the following will change the current directory to `fixtures` located in the root of the
/// [`BinaryBenchmarkConfig::sandbox`]
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark, Sandbox, BinaryBenchmarkConfig};
///
/// fn setup_sandbox() {
/// std::fs::create_dir("fixtures").unwrap();
/// }
///
/// #[binary_benchmark(
/// setup = setup_sandbox(),
/// config = BinaryBenchmarkConfig::default().sandbox(Sandbox::new(true))
/// )]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// .current_dir("fixtures")
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
/// # 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 expected exit status [`ExitWith`] of this [`Command`]
///
/// See also [`BinaryBenchmarkConfig::exit_with`]. This setting overwrites the setting of the
/// [`BinaryBenchmarkConfig`].
///
/// # Examples
///
/// If the command is expected to exit with a specific code, for example `100`:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark, ExitWith};
///
/// #[binary_benchmark]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// .exit_with(ExitWith::Code(100))
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
///
/// If a command is expected to fail, but the exit code doesn't matter:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// # use iai_callgrind::main;
/// use iai_callgrind::{binary_benchmark_group, binary_benchmark, ExitWith};
///
/// #[binary_benchmark]
/// fn bench_binary() -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// .exit_with(ExitWith::Failure)
/// .build()
/// }
///
/// binary_benchmark_group!(
/// name = my_group;
/// benchmarks = bench_binary
/// );
/// # fn main() {
/// # main!(binary_benchmark_groups = my_group);
/// # }
/// ```
pub fn exit_with(&mut self, exit_with: ExitWith) -> &mut Self {
self.0.config.exit_with = Some(exit_with.into());
self
}
/// Finalize and build this [`Command`]
///
/// # Examples
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// use iai_callgrind::Command;
///
/// let command: Command = Command::new(env!("CARGO_BIN_EXE_my-exe"))
/// .arg("foo")
/// .build();
/// ```
pub fn build(&mut self) -> Self {
self.clone()
}
}
impl From<&mut Command> for Command {
fn from(value: &mut Command) -> Self {
value.clone()
}
}
impl From<&Command> for Command {
fn from(value: &Command) -> Self {
value.clone()
}
}
impl Delay {
/// Instantiate a [`Delay`] which will wait until a path exists ([`Path::exists`]).
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
///
/// use iai_callgrind::{Command, Delay};
///
/// let command = Command::new("echo").delay(Delay::from_path("/your/path/to/wait/for"));
/// ```
pub fn from_path<T>(path: T) -> Self
where
T: Into<PathBuf>,
{
Self(internal::InternalDelay {
kind: DelayKind::PathExists(path.into()),
..Default::default()
})
}
/// Instantiate a [`Delay`] which will wait until successful TCP connect
/// ([`std::net::TcpStream::connect`]).
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
///
/// use std::net::SocketAddr;
///
/// use iai_callgrind::{Command, Delay};
///
/// let command = Command::new("echo").delay(Delay::from_tcp_socket(
/// "127.0.0.1:31000".parse::<SocketAddr>().unwrap(),
/// ));
/// ```
pub fn from_tcp_socket<T>(addr: T) -> Self
where
T: Into<SocketAddr>,
{
Self(internal::InternalDelay {
kind: DelayKind::TcpConnect(addr.into()),
..Default::default()
})
}
/// Instantiate a [`Delay`] which will wait until a UDP response is received after
/// sending the UDP request. The poll duration is also used as the reconnect and request resend
/// interval. ([`std::net::UdpSocket::bind`], [`std::net::UdpSocket::connect`],
/// [`std::net::UdpSocket::recv`]).
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
///
/// use std::net::SocketAddr;
///
/// use iai_callgrind::{Command, Delay};
///
/// let command = Command::new("echo").delay(Delay::from_udp_request(
/// "127.0.0.1:34000".parse::<SocketAddr>().unwrap(),
/// vec![1],
/// ));
/// ```
pub fn from_udp_request<T, U>(addr: T, req: U) -> Self
where
T: Into<SocketAddr>,
U: Into<Vec<u8>>,
{
Self(internal::InternalDelay {
kind: DelayKind::UdpResponse(addr.into(), req.into()),
..Default::default()
})
}
/// Instantiate a [`Delay`] waiting until an event has happened.
///
/// The possible events are defined in [`DelayKind`].
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
///
/// use std::time::Duration;
///
/// use iai_callgrind::{Command, Delay, DelayKind};
///
/// let command = Command::new("echo").delay(Delay::new(DelayKind::DurationElapse(
/// Duration::from_secs(15),
/// )));
/// ```
pub fn new(kind: DelayKind) -> Self {
Self(internal::InternalDelay {
kind,
..Default::default()
})
}
/// Update the [`Delay`] poll interval.
///
/// The poll interval should be considered together with the [`Delay::timeout`], and ideally
/// should have a value of `n * timeout duration`.
///
/// In case the poll interval is set to a value `>=` timeout duration it is attempted to set
/// the poll interval to a value of `timeout duration - 5ms`.
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
///
/// use std::net::SocketAddr;
/// use std::time::Duration;
///
/// use iai_callgrind::{Command, Delay};
///
/// let command = Command::new("echo").delay(
/// Delay::from_udp_request("127.0.0.1:34000".parse::<SocketAddr>().unwrap(), vec![1])
/// .poll(Duration::from_millis(150)),
/// );
/// ```
pub fn poll<T: Into<Duration>>(mut self, duration: T) -> Self {
self.0.poll = Some(duration.into());
self
}
/// Update the [`Delay`] timeout interval.
///
/// The timeout duration should be considered together with the poll interval. For further
/// details please refer to [`Delay::poll`]. The minimum timeout duration is `10ms`.
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
///
/// use std::net::SocketAddr;
/// use std::time::Duration;
///
/// use iai_callgrind::{Command, Delay};
/// let command = Command::new("echo").delay(
/// Delay::from_tcp_socket("127.0.0.1:31000".parse::<SocketAddr>().unwrap())
/// .timeout(Duration::from_secs(5)),
/// );
/// ```
pub fn timeout<T: Into<Duration>>(mut self, duration: T) -> Self {
self.0.timeout = Some(duration.into());
self
}
}
impl<T> From<T> for Delay
where
T: Into<Duration>,
{
/// Instantiate a [`Delay`] which will wait until the duration has elapsed.
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
///
/// use std::time::Duration;
///
/// use iai_callgrind::{Command, Delay};
///
/// let command = Command::new("echo").delay(Delay::from(Duration::from_secs(10)));
/// ```
fn from(duration: T) -> Self {
Self(internal::InternalDelay {
kind: DelayKind::DurationElapse(duration.into()),
..Default::default()
})
}
}
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 Sandbox {
/// Create a new `Sandbox` builder
///
/// Per default, a [`Command`] is not run in a `Sandbox` because setting up a `Sandbox` usually
/// involves some user interaction, for example copying fixtures into it with
/// [`Sandbox::fixtures`].
///
/// The temporary directory is only created immediately before the `setup` and the [`Command`]
/// are executed.
///
/// # Examples
///
/// Enable the sandbox for all benchmarks
///
/// ```rust
/// use iai_callgrind::{BinaryBenchmarkConfig, Sandbox, main};
/// # use iai_callgrind::binary_benchmark_group;
/// # binary_benchmark_group!(name = my_group; benchmarks = |_group| {});
/// # fn main() {
/// main!(
/// config = BinaryBenchmarkConfig::default().sandbox(Sandbox::new(true));
/// binary_benchmark_groups = my_group
/// );
/// # }
/// ```
pub fn new(enabled: bool) -> Self {
Self(internal::InternalSandbox {
enabled: Some(enabled),
..Default::default()
})
}
/// Specify the directories and/or files you want to copy into the root of the `Sandbox`
///
/// The paths are interpreted relative to the workspace root as it is reported by `cargo`. In a
/// multi-crate project this is the directory with the top-level `Cargo.toml`. Otherwise, it is
/// simply the directory with your `Cargo.toml` file in it.
///
/// # Examples
///
/// Assuming you crate's binary is called `my-foo` taking a file path as the first argument and
/// the fixtures directory is `$WORKSPACE_ROOT/benches/fixtures` containing a fixture
/// `fix_1.txt`:
///
/// ```rust
/// # macro_rules! env { ($m:tt) => {{ "/some/path" }} }
/// # use iai_callgrind::{binary_benchmark_group, main};
/// use iai_callgrind::{binary_benchmark, BinaryBenchmarkConfig, Sandbox};
///
/// #[binary_benchmark]
/// #[bench::fix_1(
/// args = ("fix_1.txt"),
/// config = BinaryBenchmarkConfig::default()
/// .sandbox(Sandbox::new(true)
/// .fixtures(["benches/fixtures/fix_1.txt"])
/// )
/// )]
/// fn bench_with_fixtures(path: &str) -> iai_callgrind::Command {
/// iai_callgrind::Command::new(env!("CARGO_BIN_EXE_my-foo"))
/// .arg(path)
/// .build()
/// }
/// # binary_benchmark_group!(name = my_group; benchmarks = bench_with_fixtures);
/// # fn main() { main!(binary_benchmark_groups = my_group); }
/// ```
pub fn fixtures<I, T>(&mut self, paths: T) -> &mut Self
where
I: Into<PathBuf>,
T: IntoIterator<Item = I>,
{
self.0.fixtures.extend(paths.into_iter().map(Into::into));
self
}
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use super::*;
#[rstest]
#[case::empty("")]
#[case::simple_invalid("-")]
#[case::when_0_char_minus_1("a\x2f")]
#[case::when_9_char_plus_1("a\x3a")]
#[case::when_big_a_char_minus_1("\x40")]
#[case::when_big_z_char_plus_1("\x5b")]
#[case::when_low_a_char_minus_1("\x60")]
#[case::when_low_z_char_plus_1("\x7b")]
#[case::invalid_2nd("a-")]
#[case::invalid_3rd("ab-")]
#[case::all_invalid("---")]
#[case::number_as_first("0")]
// This would be a valid rust identifier, but we don't allow the whole set
#[case::non_ascii_1st("µ")]
#[case::non_ascii_2nd("aµ")]
#[case::non_ascii_3rd("aaµ")]
#[case::non_ascii_middle("aµa")]
fn test_benchmark_id_validate_when_error(#[case] id: &str) {
let id = BenchmarkId::new(id);
assert!(id.validate().is_err());
}
#[rstest]
#[case::lowercase_a("a")]
#[case::lowercase_b("b")]
#[case::lowercase_m("m")]
#[case::lowercase_y("y")]
#[case::lowercase_z("z")]
#[case::uppercase_a("A")]
#[case::uppercase_b("B")]
#[case::uppercase_n("N")]
#[case::uppercase_y("Y")]
#[case::uppercase_z("Z")]
#[case::zero_2nd("a0")]
#[case::one_2nd("a1")]
#[case::eight_2nd("a8")]
#[case::nine_2nd("a9")]
#[case::number_middle("b4t")]
#[case::underscore("_")]
#[case::only_underscore("___")]
#[case::underscore_last("a_")]
#[case::mixed_all("auAEwer9__2xcd")]
fn test_benchmark_id_validate(#[case] id: &str) {
let id = BenchmarkId::new(id);
assert!(id.validate().is_ok());
}
#[rstest]
#[case::empty("", "Invalid id: Cannot be empty")]
#[case::non_ascii_first(
"µ",
"Invalid id 'µ': Encountered non-ascii character as first character"
)]
#[case::multibyte_middle(
"aµ",
"Invalid id 'aµ' at position 1: Encountered non-ascii character"
)]
#[case::non_ascii_middle("a-", "Invalid id 'a-' at position 1: Invalid character '-'")]
#[case::invalid_first("-", "Invalid id '-': As first character is '-' not allowed")]
fn test_benchmark_id_validate_error_message(#[case] id: &str, #[case] message: &str) {
let id = BenchmarkId::new(id);
assert_eq!(
id.validate()
.expect_err("Validation should return an error"),
message
);
}
}