我和几个编程领域的人有一场友好的竞争,最近我们对编写高效的代码非常感兴趣。我们面临的挑战是,不惜任何代价(可读性、可重用性等)来优化代码(就cpu时间和复杂性而言)。
问题是,现在我们需要比较我们的代码,看看哪种方法比其他方法更好,但是我们不知道有什么工具可以达到这个目的。
我的问题是,有什么(!)将一段代码作为输入并计算运行它所需的失败或cpu指令数量的工具?有什么工具可以衡量代码的优化程度吗?
目标语言是c++,但是很高兴知道这些工具是否也适用于java。
发布于 2012-09-09 16:40:14
这里有一个小小的C++11秒表,我喜欢在需要计时的时候推出它:
#include <chrono>
#include <ctime>
template <typename T> class basic_stopwatch
{
typedef T clock;
typename clock::time_point p;
typename clock::duration d;
public:
void tick() { p = clock::now(); }
void tock() { d += clock::now() - p; }
void reset() { d = clock::duration::zero(); }
template <typename S> unsigned long long int report() const
{
return std::chrono::duration_cast<S>(d).count();
}
unsigned long long int report_ms() const
{
return report<std::chrono::milliseconds>();
}
basic_stopwatch() : p(), d() { }
};
struct c_clock
{
typedef std::clock_t time_point;
typedef std::clock_t duration;
static time_point now() { return std::clock(); }
};
template <> unsigned long long int basic_stopwatch<c_clock>::report_ms() const
{
return 1000. * double(d) / double(CLOCKS_PER_SEC);
}
typedef basic_stopwatch<std::chrono::high_resolution_clock> stopwatch;
typedef basic_stopwatch<c_clock> cstopwatch;用法:
stopwatch sw;
sw.tick();
run_long_code();
sw.tock();
std::cout << "This took " << sw.report_ms() << "ms.\n";在任何适当的实现中,默认的high_resolution_clock都应该提供非常准确的计时信息。
https://stackoverflow.com/questions/12340824
复制相似问题