如何在 Zedboard 上检查 C++ 程序的时间性能

How to check time performances in a C++ program on Zedboard

我已经在 Zedboard 上实现了 C++ 代码。它编译和运行完美,但现在我想检查性能以优化某些功能。 我在这里检查了一些线程 (Testing the performance of a C++ app) and here (Timer function to provide time in nano seconds using C++),但我真的不明白如何应用它的 mon 代码 ...

澄清一下:我不擅长 C++,我从来没有真正正式地学习过这门语言,只是在特定的库中使用过几次。我什至不是我正在使用的代码的作者(教授给我的)。

我的目标是检查在 Zedboard 上执行程序时在每个函数和全局上花费的时间。代码位于 SD 卡上的 Linux 图像上,电路板以此图像启动。它使用图像处理应用程序的 opencv 库。我使用 g++ 4.6.3 作为编译器。

预先感谢您的回答!

您可以使用 <chrono> header 创建一个简单的计时器 class。像这样:

class Timer
{
public:
    using clock = std::chrono::steady_clock;

    void clear() { start(); tse = tsb; }
    void start() { tsb = clock::now(); }
    void stop()  { tse = clock::now(); }

    auto nsecs() const
    {
        using namespace std::chrono;
        return duration_cast<nanoseconds>(tse - tsb).count();
    }

    double usecs() const { return double(nsecs()) / 1000.0; }
    double msecs() const { return double(nsecs()) / 1000000.0; }
    double  secs() const { return double(nsecs()) / 1000000000.0; }

    friend std::ostream& operator<<(std::ostream& o, Timer const& timer)
    {
        return o << timer.secs();
    }

private:
    clock::time_point tsb;
    clock::time_point tse;
};

您可以像这样简单地使用它:

Timer timer;

timer.start();

// do some stuff
std::this_thread::sleep_for(std::chrono::milliseconds(600));

timer.stop();

std::cout << timer << " seconds" << '\n';

编辑:POSIX 系统上,如果 <chrono> 不可用,您可以使用 clock_gettime()

class Timer
{
public:
    void clear() { start(); tse = tsb; }
    void start() { clock_gettime(CLOCK_MONOTONIC, &tsb); }
    void stop() { clock_gettime(CLOCK_MONOTONIC, &tse); }

    long nsecs() const
    {
        long b = (tsb.tv_sec * 1000000000) + tsb.tv_nsec;
        long e = (tse.tv_sec * 1000000000) + tse.tv_nsec;
        return e - b;
    }

    double usecs() const { return double(nsecs()) / 1000.0; }
    double msecs() const { return double(nsecs()) / 1000000.0; }
    double  secs() const { return double(nsecs()) / 1000000000.0; }

    friend std::ostream& operator<<(std::ostream& o, Timer const& timer)
    {
        return o << timer.secs();
    }

private:
    timespec tsb;
    timespec tse;
};

我找到了一个不令人满意的解决方案,但我想我仍然可以 post 如果它有任何帮助的话。

我使用了 <time.h> 中定义的 gettimeofday() 函数。它使用起来非常简单,但有一些缺陷,我稍后会解释:

timeval t1, t2;
gettimeofday(&t1, NULL);
/* some function */
gettimeofday(&t2, NULL);
double time;
time = (t2.tv_sec - t1.tv_sec)*1000.0 + (t2.tv_usec - t1.tv_usec)/1000.0; 
cout << time << "ms" << "\n";

通过这种方式,我以毫秒为单位测量时间并将其显示在屏幕上。但是 gettimeofday 不是基于计算机时钟而是基于实际时间。需要明确的是,两次调用之间经过的时间确实包含我的函数,但也包含 Ubuntu 后台的所有进程 运行。换句话说,这并没有给我函数执行所花费的精确时间,而是一个稍高的值。

编辑:我再次找到了另一个解决方案,使用 <time.h> 中的 clock() 函数,与我用以前的方法得到的结果相比,结果似乎是正确的。不幸的是,精度不够,因为它只给出了一个以秒为单位的数字,只有 3 位数字。