歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux編程 >> Linux編程

C/C++ 獲取時間間隔的方法

clock函數方式

Linux平台下C/C++中獲取時間間隔的方法,一種比較普遍的認識是采用clock函數

clock_t clock ( void );

Returns the number of clock ticks elapsed since the program was launched.

The macro constant expression CLOCKS_PER_SEC specifies the relation between a clock tick and a second (clock ticks per second).

The initial moment of reference used by clock as the beginning of the program execution may vary between platforms. To calculate the actual processing times of a program, the value returned by clock should be compared to a value returned by an initial call to clock.

通過兩次調用clock函數可以得到起始時間和結束時間,從而得到毫秒級的時間差


gettimeofday函數方式

C/C++語言中有個timeval結構是可以精確到毫秒,可以利用timeval來記錄起始時間和結束時間

           struct timeval {
               time_t      tv_sec;     /* seconds */
               SUSEconds_t tv_usec;    /* microseconds */
           };

通過調用gettimeofday函數可以得到用timeval結構記錄的當前時間

int gettimeofday(struct timeval *tv, struct timezone *tz);


具體實現

#include <time.h>

#include <sys/time.h>

class ClockTool
{
    public:
    ClockTool()
        : m_begin(0), m_end(0)
    {
    }


    inline void begin()
    {
        m_begin = clock();
    }


    inline void end()
    {
        m_end = clock();
    }


    inline void reset()
    {
        m_begin = 0;
        m_end = 0;
    }


    float getInterval()
    {
        if (m_end < m_begin)
        {
            return 0;
        }
        return (double)(m_end - m_begin)/CLOCKS_PER_SEC;
    }


    private:
    clock_t m_begin;
    clock_t m_end;
};


class TimeTool
{
    public:
    TimeTool()
    {
        reset();
    }


    inline void begin()
    {
        gettimeofday(&m_begin, NULL);
    }


    inline void end()
    {
        gettimeofday(&m_end, NULL);
    }


    inline void reset()
    {
        memset(&m_begin, 0, sizeof(struct timeval));
        memset(&m_end, 0, sizeof(struct timeval));
    }


    float getInterval()
    {
        if (m_end.tv_usec < m_begin.tv_usec)
        {
            m_end.tv_usec += 1000;
            m_end.tv_sec = m_end.tv_sec - 1;
        }
        return (m_end.tv_sec - m_begin.tv_sec) + (m_end.tv_usec - m_begin.tv_usec) / 1000000.0;
    }


    private:
    struct timeval m_begin;
    struct timeval m_end;
};

Copyright © Linux教程網 All Rights Reserved