bench-sum-cols.cc 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // -*- mode: c++; coding: utf-8 -*-
  2. // ra-ra/bench - Various ways to sum columns.
  3. // (c) Daniel Llorens - 2016-2017
  4. // This library is free software; you can redistribute it and/or modify it under
  5. // the terms of the GNU Lesser General Public License as published by the Free
  6. // Software Foundation; either version 3 of the License, or (at your option) any
  7. // later version.
  8. #include <iostream>
  9. #include <iomanip>
  10. #include "ra/bench.hh"
  11. using std::cout, std::endl, std::flush, ra::TestRecorder;
  12. using real = double;
  13. int main()
  14. {
  15. TestRecorder tr(cout);
  16. cout.precision(4);
  17. auto bench =
  18. [&tr](char const * tag, int m, int n, int reps, auto && f)
  19. {
  20. ra::Big<real, 2> a({m, n}, ra::_0 - ra::_1);
  21. ra::Big<real, 1> ref({m}, 0);
  22. ref += a*reps;
  23. ra::Big<real, 1> c({m}, ra::none);
  24. auto bv = Benchmark().repeats(reps).runs(3)
  25. .once_f([&](auto && repeat) { c = 0.; repeat([&]() { f(c, a); }); });
  26. tr.info(std::setw(5), std::fixed, Benchmark::avg(bv)/(m*n)/1e-9, " ns [",
  27. Benchmark::stddev(bv)/(m*n)/1e-9 ,"] ", tag).test_eq(ref, c);
  28. };
  29. auto bench_all =
  30. [&](int m, int n, int reps)
  31. {
  32. tr.section(m, " x ", n, " times ", reps);
  33. bench("raw", m, n, reps,
  34. [](auto & c, auto const & a)
  35. {
  36. real const * __restrict__ ap = a.data();
  37. real * __restrict__ cp = c.data();
  38. ra::dim_t const m = a.len(0);
  39. ra::dim_t const n = a.len(1);
  40. for (ra::dim_t i=0; i!=m; ++i) {
  41. for (ra::dim_t j=0; j!=n; ++j) {
  42. cp[i] += ap[i*n+j];
  43. }
  44. }
  45. });
  46. bench("sideways", m, n, reps,
  47. [](auto & c, auto const & a)
  48. {
  49. for (int j=0, jend=a.len(1); j<jend; ++j) {
  50. c += a(ra::all, j);
  51. }
  52. });
  53. bench("accumcols", m, n, reps,
  54. [](auto & c, auto const & a)
  55. {
  56. for_each([](auto & c, auto && a) { c += sum(a); }, c, iter<1>(a));
  57. });
  58. bench("wrank1", m, n, reps,
  59. [](auto & c, auto const & a)
  60. {
  61. for_each(ra::wrank<0, 0>([](auto & c, auto && a) { c += a; }), c, a);
  62. });
  63. bench("framematch", m, n, reps,
  64. [](auto & c, auto const & a)
  65. {
  66. c += a; // bump c after each row, so it cannot be raveled
  67. });
  68. };
  69. bench_all(1, 1000000, 20);
  70. bench_all(10, 100000, 20);
  71. bench_all(100, 10000, 20);
  72. bench_all(1000, 1000, 20);
  73. bench_all(10000, 100, 20);
  74. bench_all(100000, 10, 20);
  75. bench_all(1000000, 1, 20);
  76. bench_all(1, 10000, 2000);
  77. bench_all(10, 1000, 2000);
  78. bench_all(100, 100, 2000);
  79. bench_all(1000, 10, 2000);
  80. bench_all(10000, 1, 2000);
  81. return tr.summary();
  82. }