如何比较两段代码的性能 [英] How to compare performance of two pieces of codes

查看:218
本文介绍了如何比较两段代码的性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与编程领域的几个人进行了一场友好的竞争,最近我们对编写高效的代码非常感兴趣.我们面临的挑战是尝试不惜一切代价(可读性,可重用性等)优化代码(从cpu时间和复杂性的角度来看).

I have a friendly competition with couple of guys in the field of programming and recently we have become so interested in writing efficient code. Our challenge was to try to optimize the code (in sense of cpu time and complexity) at any cost (readability, reusability, etc).

问题是,现在我们需要比较我们的代码,看看哪种方法比其他方法更好,但是我们不知道用于此目的的任何工具.

The problem is, now we need to compare our codes and see which approach is better comparing to the others but we don't know any tools for this purpose.

我的问题是,有一些(任何!)工具需要一段代码 作为输入并计算触发器或CPU指令的数量 要运行它吗?有没有什么工具可以衡量乐观程度 代码?

My question is, are there some (any!) tools that takes a piece of code as input and calculates the number of flops or cpu instructions necessary for running it? Is there any tool can measure the optimacy of a code?

P.S.目标语言是c ++,但是很高兴知道这样的工具是否也适用于Java.

P.S. The target language is c++ but would be nice to know if such tools exists also for java.

推荐答案

下面是我需要计时的C ++ 11秒表:

Here's a little C++11 stopwatch I like to roll out when I need to time something:

#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应该提供非常准确的时序信息.

On any decent implementation, the default high_resolution_clock should give very accurate timing information.

这篇关于如何比较两段代码的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆