Category Archives: Mark

C++11下计算任意函数的执行时间

之前在写优化后的Sieve of Eratosthenes筛法时,写了一个函数用于计算另一个给定函数的执行时间,但是还不够通用,今天用C++11写了一个通用的版本。

#include <chrono>
#include <functional>
#include <future>
#include <stdio.h>
#include <type_traits>

/**
 *  @brief Give the elapsed time of any function
 *
 *  @param func_name Used in printf
 *  @param func The function that to be measured
 *  @param args Arguments of the given function
 *
 *  @return The return value of the given function
 */
template <class Function, class ... Args>
std::future<typename std::result_of<Function(Args...)>::type> runtime(const char * func_name, Function&& func, Args&&... args) {
    typedef typename std::result_of<Function(Args...)>::type return_type;
    typedef std::packaged_task<return_type()> task;
    auto t = std::make_shared<task>(std::bind(std::forward<Function>(func), std::forward<Args>(args)...));
    auto start = chrono::high_resolution_clock::now();
    auto ret = t->get_future();
    {
        (*t)();
    }
    auto end = chrono::high_resolution_clock::now();
    printf("%s: %lfs\n", func_name, ((chrono::duration<double>)((end - start))).count());
    return ret;
}