代码之家  ›  专栏  ›  技术社区  ›  Jack BeNimble

如何计算C++中的时差

c++
  •  80
  • Jack BeNimble  · 技术社区  · 16 年前

    计算C++中时差的最好方法是什么?我在计时程序的执行速度,所以我对毫秒感兴趣。更好的是,秒,毫秒……

    接受的答案有效,但需要包括CTIME或时间.h,如评论中所述。

    13 回复  |  直到 7 年前
        1
  •  107
  •   Diego Sevilla    11 年前

    std::clock() 功能。

    const clock_t begin_time = clock();
    // do something
    std::cout << float( clock () - begin_time ) /  CLOCKS_PER_SEC;
    

    如果您想为自己计算执行时间(而不是为用户计算),最好以时钟周期(而不是秒)为单位进行计算。

    编辑:
    负责的头文件- <ctime> <time.h>

        2
  •  32
  •   gongzhitaao    11 年前

    如果您使用C++ 11,这里是一个简单的包装器(见此 gist ):

    #include <iostream>
    #include <chrono>
    
    class Timer
    {
    public:
        Timer() : beg_(clock_::now()) {}
        void reset() { beg_ = clock_::now(); }
        double elapsed() const { 
            return std::chrono::duration_cast<second_>
                (clock_::now() - beg_).count(); }
    
    private:
        typedef std::chrono::high_resolution_clock clock_;
        typedef std::chrono::duration<double, std::ratio<1> > second_;
        std::chrono::time_point<clock_> beg_;
    };
    

    或者对于C++ 03在*NIX上:

    #include <iostream>
    #include <ctime>
    
    class Timer
    {
    public:
        Timer() { clock_gettime(CLOCK_REALTIME, &beg_); }
    
        double elapsed() {
            clock_gettime(CLOCK_REALTIME, &end_);
            return end_.tv_sec - beg_.tv_sec +
                (end_.tv_nsec - beg_.tv_nsec) / 1000000000.;
        }
    
        void reset() { clock_gettime(CLOCK_REALTIME, &beg_); }
    
    private:
        timespec beg_, end_;
    };
    

    使用示例:

    int main()
    {
        Timer tmr;
        double t = tmr.elapsed();
        std::cout << t << std::endl;
    
        tmr.reset();
        t = tmr.elapsed();
        std::cout << t << std::endl;
        return 0;
    }
    
        3
  •  30
  •   Jeremy CD    16 年前

    我会认真考虑使用boost,特别是boost::posix_time::ptime和boost::posix_time::time_duration(在 http://www.boost.org/doc/libs/1_38_0/doc/html/date_time/posix_time.html )

    它是跨平台的,易于使用,根据我的经验,它提供了操作系统提供的最高级别的时间分辨率。可能也非常重要;它提供了一些非常好的IO操作员。

    要使用它来计算程序执行的差异(以微秒计;可能是杀伤力过大),它看起来像这样[浏览器编写,未测试]:

    ptime time_start(microsec_clock::local_time());
    //... execution goes here ...
    ptime time_end(microsec_clock::local_time());
    time_duration duration(time_end - time_start);
    cout << duration << '\n';
    
        4
  •  13
  •   Gabi Davar    13 年前

    Boost 1.46.0及以上版本包括 Chrono 图书馆:

    线程时钟类提供对实际线程壁时钟的访问,即 调用线程的实时CPU时钟。线的相对 可以通过调用线程_clock::now()来获取当前时间。

    #include <boost/chrono/thread_clock.hpp>
    {
    ...
        using namespace boost::chrono;
        thread_clock::time_point start = thread_clock::now();
        ...
        thread_clock::time_point stop = thread_clock::now();  
        std::cout << "duration: " << duration_cast<milliseconds>(stop - start).count() << " ms\n";
    
        5
  •  11
  •   aJ.    16 年前

    在Windows中:使用 GetTickCount

    //GetTickCount defintition
    #include <windows.h>
    int main()
    {
    
        DWORD dw1 = GetTickCount();
    
        //Do something 
    
        DWORD dw2 = GetTickCount();
    
        cout<<"Time difference is "<<(dw2-dw1)<<" milliSeconds"<<endl;
    
    }
    
        6
  •  10
  •   Sumsuddin Shojib    7 年前

    我添加了这个答案来澄清 answer 显示可能不是所需时间的CPU时间。因为根据 the reference CPU时间和挂钟时间 . 墙时钟时间是显示实际运行时间的时间,而不考虑任何其他条件,如CPU由其他进程共享。例如,我使用多个处理器来完成某个任务,CPU时间很长 18S 它实际发生的地方 2S 在实际的挂钟时间。

    为了得到你的实际时间,

    #include <chrono>
    
    auto t_start = std::chrono::high_resolution_clock::now();
    // the work...
    auto t_end = std::chrono::high_resolution_clock::now();
    
    double elaspedTimeMs = std::chrono::duration<double, std::milli>(t_end-t_start).count();
    
        7
  •  8
  •   Richard    11 年前

    您也可以使用 clock_gettime . 此方法可用于测量:

    1. 全系统实时时钟
    2. 全系统单调时钟
    3. 每进程CPU时间
    4. 每个进程线程的CPU时间

    代码如下:

    #include < time.h >
    #include <iostream>
    int main(){
      timespec ts_beg, ts_end;
      clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts_beg);
      clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts_end);
      std::cout << (ts_end.tv_sec - ts_beg.tv_sec) + (ts_end.tv_nsec - ts_beg.tv_nsec) / 1e9 << " sec";
    }
    

    `

        8
  •  6
  •   fengshaun    16 年前

    如果您在Unix上,可以使用 time 要获得执行时间:

    $ g++ myprog.cpp -o myprog
    $ time ./myprog
    
        9
  •  5
  •   v3.    16 年前

    附带说明:如果您在Windows上运行,并且确实需要精确性,则可以使用 QueryPerformanceCounter . 它给你时间(潜在的) 纳米技术 秒。

        10
  •  4
  •   user1823890    10 年前

    对我来说,最简单的方法是:

    #include <boost/timer.hpp>
    
    boost::timer t;
    double duration;
    
    t.restart();
    /* DO SOMETHING HERE... */
    duration = t.elapsed();
    
    t.restart();
    /* DO OTHER STUFF HERE... */
    duration = t.elapsed();
    

    使用这段代码,你不必做经典的 end - start .

    享受你最喜欢的方法。

        11
  •  3
  •   Jared Oberhaus    16 年前

    获取系统时间,以毫秒为单位,从开始到结束,再减去。

    要获得自1970年以来在posix中的毫秒数,您需要编写:

    struct timeval tv;
    
    gettimeofday(&tv, NULL);
    return ((((unsigned long long)tv.tv_sec) * 1000) +
            (((unsigned long long)tv.tv_usec) / 1000));
    

    要在Windows上获取自1601年以来的毫秒数,您需要写入:

    SYSTEMTIME systime;
    FILETIME filetime;
    
    GetSystemTime(&systime);
    if (!SystemTimeToFileTime(&systime, &filetime))
        return 0;
    
    unsigned long long ns_since_1601;
    ULARGE_INTEGER* ptr = (ULARGE_INTEGER*)&ns_since_1601;
    
    // copy the result into the ULARGE_INTEGER; this is actually
    // copying the result into the ns_since_1601 unsigned long long.
    ptr->u.LowPart = filetime.dwLowDateTime;
    ptr->u.HighPart = filetime.dwHighDateTime;
    
    // Compute the number of milliseconds since 1601; we have to
    // divide by 10,000, since the current value is the number of 100ns
    // intervals since 1601, not ms.
    return (ns_since_1601 / 10000);
    

    如果您希望规范化Windows应答,使它也返回1970年以来的毫秒数,那么您必须将应答调整为11644473600000毫秒。但如果你所关心的只是过去的时间,那就没有必要了。

        12
  •  2
  •   dvhh    9 年前

    如果使用:

    tstart = clock();
    
    // ...do something...
    
    tend = clock();
    

    然后,您将需要以下内容以秒为单位获得时间:

    time = (tend - tstart) / (double) CLOCKS_PER_SEC;
    
        13
  •  0
  •   Miek    12 年前

    这对于Intel Mac 10.7来说似乎很好:

    #include <time.h>
    
    time_t start = time(NULL);
    
    
        //Do your work
    
    
    time_t end = time(NULL);
    std::cout<<"Execution Time: "<< (double)(end-start)<<" Seconds"<<std::endl;