开发者

millisecond-accurate benchmarking in C++?

开发者 https://www.devze.com 2023-01-17 10:18 出处:网络
I do not really wish to profile because I was wanting to do many different small benchmarks on different simple functions. For the life of me I cannot find a way to record the amoun开发者_StackOverflo

I do not really wish to profile because I was wanting to do many different small benchmarks on different simple functions. For the life of me I cannot find a way to record the amoun开发者_StackOverflow中文版t of milliseconds in C++, I am using Linux by the way.

Can you suggest the method to get the system clock in milliseconds (I may settle with seconds if I cannot find an easy way..) and what header they are included in?


using gettimeofday function from sys/time.h header file, i use this class:

#include <cstdlib>
#include <sys/time.h>

class Timer
{
    timeval timer[2];

  public:

    timeval start()
    {
        gettimeofday(&this->timer[0], NULL);
        return this->timer[0];
    }

    timeval stop()
    {
        gettimeofday(&this->timer[1], NULL);
        return this->timer[1];
    }

    int duration() const
    {
        int secs(this->timer[1].tv_sec - this->timer[0].tv_sec);
        int usecs(this->timer[1].tv_usec - this->timer[0].tv_usec);

        if(usecs < 0)
        {
            --secs;
            usecs += 1000000;
        }

        return static_cast<int>(secs * 1000 + usecs / 1000.0 + 0.5);
    }
};

for example:

#include <iostream>
#include <string>
#include <sstream>

int main()
{
    Timer tm;
    std::ostringstream ooo;
    std::string str;

    tm.start();
    for(int i = 0; i < 10000000; ++i)
    {
        ooo << "This is a string. ";
    }
    tm.stop();
    std::cout << "std::ostingstream -> " << tm.duration() << std::endl;

    tm.start();
    for(int i = 0; i < 10000000; ++i)
    {
        str += "This is a string. ";
    }
    tm.stop();
    std::cout << "std::string -> " << tm.duration() << std::endl;
}


If you are using x86 CPU, you can use rdtsc assembler instructions http://en.wikipedia.org/wiki/Rdtsc in order to get number of CPU clocks between execution of two (or more) commands. But: 1. All rdtsc commands should run on same CPU core (in case if you have multi core CPU). 2. CPU should run in constant clock frequency (CPU power management should be disabled).

Dima

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号