开发者

Adding a timer in a C++ loop

I found some simple Pi calculation programs written in C++. My knowledge of C++ isn't that good(none to be exact), but how do i go about implementing a timer to tell me how long it took for the program to calculate the Pi number?

开发者_Python百科

Like: Pi calculation finished in X seconds or minutes or hours etc.


#include <cstdio>
#include <ctime>
using namespace std;

int main()
{
   clock_t start = clock();
   /* Code you want timed here */
   printf("Time elapsed: %f\n", ((double)clock() - start) / CLOCKS_PER_SEC);
}


#include <sys/time.h>
class CBenchmark
{
    public:
        CBenchmark(void) throw() :
            m_startTime(0),m_finalTime(0)
    {}

        void start(void) throw()
        {
            m_startTime=getTime();
            return;
        }

        void stop(void) throw()
        {
            m_finalTime=getTime();
            return;
        }

        size_t elapsedTime(void) throw()
        {
            return m_finalTime-m_startTime;
        }
    protected:
        size_t getTime(void) throw()
        {
            timeval tp;
            gettimeofday(&tp,NULL);
            return tp.tv_sec*1e6+tp.tv_usec;
        }

        size_t m_startTime;
        size_t m_finalTime;
};
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜