bench_move_semantics.cpp 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // This file is part of Eigen, a lightweight C++ template library
  2. // for linear algebra.
  3. //
  4. // Copyright (C) 2020 Sebastien Boisvert <seb@boisvert.info>
  5. //
  6. // This Source Code Form is subject to the terms of the Mozilla
  7. // Public License v. 2.0. If a copy of the MPL was not distributed
  8. // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
  9. #include "BenchTimer.h"
  10. #include "../test/MovableScalar.h"
  11. #include <Eigen/Core>
  12. #include <iostream>
  13. #include <utility>
  14. template <typename MatrixType>
  15. void copy_matrix(MatrixType& m)
  16. {
  17. MatrixType tmp(m);
  18. m = tmp;
  19. }
  20. template <typename MatrixType>
  21. void move_matrix(MatrixType&& m)
  22. {
  23. MatrixType tmp(std::move(m));
  24. m = std::move(tmp);
  25. }
  26. template<typename Scalar>
  27. void bench(const std::string& label)
  28. {
  29. using MatrixType = Eigen::Matrix<Eigen::MovableScalar<Scalar>,1,10>;
  30. Eigen::BenchTimer t;
  31. int tries = 10;
  32. int rep = 1000000;
  33. MatrixType data = MatrixType::Random().eval();
  34. MatrixType dest;
  35. BENCH(t, tries, rep, copy_matrix(data));
  36. std::cout << label << " copy semantics: " << 1e3*t.best(Eigen::CPU_TIMER) << " ms" << std::endl;
  37. BENCH(t, tries, rep, move_matrix(std::move(data)));
  38. std::cout << label << " move semantics: " << 1e3*t.best(Eigen::CPU_TIMER) << " ms" << std::endl;
  39. }
  40. int main()
  41. {
  42. bench<float>("float");
  43. bench<double>("double");
  44. return 0;
  45. }