为什么我的模板元代码比for循环慢?

时间:2018-03-05 13:40:47

标签: c++ loops templates template-meta-programming compile-time

我想在一组 public static final String SECURE_REMEMBER_ME_COOKIES = "yourstorefrontRememberMe"; @Resource(name = "guidCookieStrategy") private GUIDCookieStrategy guidCookieStrategy; @Override public boolean beforeController(final HttpServletRequest request, final HttpServletResponse response, final HandlerMethod handler) throws Exception { boolean redirect = true; // We only care if the request is secure if (request.isSecure()) { // Check if the handler has our annotation final RequireHardLogIn annotation = findAnnotation(handler, RequireHardLogIn.class); if (annotation != null) { final String guid = (String) request.getSession().getAttribute(SECURE_GUID_SESSION_KEY); if ((!getUserService().isAnonymousUser(getUserService().getCurrentUser()) || checkForAnonymousCheckout()) && checkForGUIDCookie(request, response, guid)) { redirect = false; } if (redirect) { if(isRememberMeCookiePresent(request)) { // If you find your guid is missing, lets recreate it. guidCookieStrategy.setCookie(request, response); return true; } else { LOG.warn((guid == null ? "missing secure token in session" : "no matching guid cookie") + ", redirecting"); getRedirectStrategy().sendRedirect(request, response, getRedirectUrl(request)); return false; } } } } return true; } protected boolean isRememberMeCookiePresent(HttpServletRequest request) { Cookie[] cookies = request.getCookies(); if ((cookies == null) || (cookies.length == 0)) { return false; } for (Cookie cookie : cookies) { if (SECURE_REMEMBER_ME_COOKIES.equals(cookie.getName())) { return cookie.getValue() != null; } } return false; } s中对位置n中的所有元素求和。总和的值存储在传递给我的函数std::array的{​​{1}}中。求和是通过递归"调用"完成的。模板化的类方法,用于对列的索引减少进行求和,直到我到达第0列,并且对于下一行都是相同的,直到我遇到第0行。

我也有一个循环版本也做同样的事情,我比较了执行这两种计算总和所需的时间。我期待看到模板化版本表现更好,但它的输出速度要慢约25倍。模板化版本有什么问题会让它变慢吗?

在开始之前,我受到this article"使用Metaprograms展开循环的启发"

该计划的输出是:

std::array

代码:

add_rows

1 个答案:

答案 0 :(得分:1)

在阅读上面的评论后,我添加了一个循环,在每次迭代后执行总和10000次打印输出。

然后在每次迭代之前用随机值初始化要求和的数组,现在时间测量显示两种方法的速度几乎相等(两者都约为15个时钟)。

#include <iostream>
#include <array>
#include <numeric>
#include <chrono>
#include <functional>
#include <random>

template<size_t num_rows, size_t row_index, size_t num_columns, size_t column_index>
class sumRow;

template<size_t num_rows, size_t row_index, size_t num_columns>
class sumRow<num_rows, row_index, num_columns, 0>
{
 public:
  static inline int result(const std::array<std::array<int, num_rows>, num_columns>& arrays) noexcept
  {
    return arrays[0][row_index];
  }
};

template<size_t num_rows, size_t row_index, size_t num_columns, size_t column_index>
class sumRow
{
 public:
  static inline int result(const std::array<std::array<int, num_rows>, num_columns>& arrays) noexcept
  {
    return arrays[column_index][row_index] + sumRow<num_rows, row_index, num_columns, column_index - 1>::result(arrays);
  }
};

// Array of arrays

template<size_t num_rows, size_t row_index, size_t num_columns>
class sumRows;

template<size_t num_rows, size_t num_columns>
class sumRows<num_rows, 0, num_columns>
{
 public:
  static inline void result(const std::array<std::array<int, num_rows>, num_columns>& arrays, std::array<int, num_rows>& result) noexcept
  {
    result[0] = sumRow<num_rows, 0, num_columns, num_columns - 1>::result(arrays);
  }
};

template<size_t num_rows, size_t row_index, size_t num_columns>
class sumRows
{
 public:
  static inline void result(const std::array<std::array<int, num_rows>, num_columns>& arrays, std::array<int, num_rows>& result) noexcept
  {
    result[row_index - 1] = sumRow<num_rows, row_index - 1, num_columns, num_columns - 1>::result(arrays);
    sumRows<num_rows, row_index - 1, num_columns>::result(arrays, result);
  }
};

template<size_t num_rows, size_t num_columns>
inline void sum_rows(const std::array<std::array<int, num_rows>, num_columns>& arrays, std::array<int, num_rows>& result)
{
  sumRows<num_rows, num_rows, num_columns>::result(arrays, result);
};

template<size_t channel_size, size_t num_channels>
inline void loop_sum(const std::array<std::array<int, channel_size>, num_channels>& channels, std::array<int, channel_size>& results) noexcept
{
  for (size_t sample_index = 0; sample_index < channel_size; ++sample_index)
  {
    int result = 0;
    for (size_t channel_index = 0; channel_index < num_channels; ++channel_index)
    {
      result += channels[channel_index][sample_index];
    }
    results[sample_index] = result;
  }
};

// Inspired by from https://stackoverflow.com/a/21995693/2996272
struct measure_cpu_clock
{
  template<typename F, typename ...Args>
  static clock_t execution(F&& func, Args&&... args)
  {
    auto start = std::clock();
    std::forward<decltype(func)>(func)(std::forward<Args>(args)...);
    return std::clock() - start;
  }
};

template<typename T>
T get_random_int(T min, T max)
{
  std::random_device rd;
  std::mt19937 gen(rd());
  std::uniform_int_distribution <T> dis(min, max);
  return dis(gen);
}

template<size_t num_values>
void print_values(std::array<int, num_values>& array)
{
  for (auto&& item : array)
  {
    std::cout << item << "<";
  }
  std::cout << std::endl;
}

const int num_columns = 850;
const int num_rows = 32;
using channel = std::array<int, num_rows>;

using func = std::function<void(const std::array<std::array<int, num_rows>, num_columns>&, std::array<int, num_rows>&)>;

clock_t perform_many(const func& f)
{
  clock_t total_execution_time = 0;
  int num_iterations = 10000;
  for (int i = 0; i < num_iterations; ++i)
  {
    std::array<channel, num_columns> channels{};
    for (auto&& item : channels)
    {
      std::iota(item.begin(), item.end(), get_random_int(0, 3));
    }
    channel results = {};

    auto start = std::clock();
    f(channels, results);
    total_execution_time += (std::clock() - start);

    print_values(results);
  }
  return total_execution_time / num_iterations;
}

int main()
{
  // Templated version
  auto template_execution_time = perform_many(sum_rows<num_rows, num_columns>);

  auto loop_execution_time = perform_many(loop_sum<num_rows, num_columns>);

  std::cout << "Templated version took: " << template_execution_time << " clocks" << std::endl;
  std::cout << "Loop version took:      " << loop_execution_time << " clock" << std::endl;

}