首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在C++中计算代码段的执行时间

如何在C++中计算代码段的执行时间
EN

Stack Overflow用户
提问于 2009-12-08 00:56:07
回答 17查看 172.8K关注 0票数 125

我必须以秒为单位计算C++代码片段的执行时间。它必须在Windows或Unix计算机上运行。

我使用下面的代码来做这件事。(在此之前导入)

代码语言:javascript
复制
clock_t startTime = clock();
// some code here
// to compute its execution duration in runtime
cout << double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;

然而,对于小的输入或简短的语句,比如a=a+ 1,我得到了"0秒“的结果。我想一定是0.0000001秒左右。

我记得Java中的System.nanoTime()在这种情况下工作得很好。然而,我不能从C++的clock()函数中获得相同的功能。

你有解决方案吗?

EN

回答 17

Stack Overflow用户

回答已采纳

发布于 2009-12-08 01:01:58

你可以使用我写的这个函数。您调用GetTimeMs64(),它使用系统时钟返回自unix纪元以来所经过的毫秒数-就像time(NULL)一样,只是以毫秒为单位。

它可以在windows和linux上运行;它是线程安全的。

请注意,在windows上,粒度是15ms;在linux上,粒度取决于实现,但通常也是15ms。

代码语言:javascript
复制
#ifdef _WIN32
#include <Windows.h>
#else
#include <sys/time.h>
#include <ctime>
#endif

/* Remove if already defined */
typedef long long int64; typedef unsigned long long uint64;

/* Returns the amount of milliseconds elapsed since the UNIX epoch. Works on both
 * windows and linux. */

uint64 GetTimeMs64()
{
#ifdef _WIN32
 /* Windows */
 FILETIME ft;
 LARGE_INTEGER li;

 /* Get the amount of 100 nano seconds intervals elapsed since January 1, 1601 (UTC) and copy it
  * to a LARGE_INTEGER structure. */
 GetSystemTimeAsFileTime(&ft);
 li.LowPart = ft.dwLowDateTime;
 li.HighPart = ft.dwHighDateTime;

 uint64 ret = li.QuadPart;
 ret -= 116444736000000000LL; /* Convert from file time to UNIX epoch time. */
 ret /= 10000; /* From 100 nano seconds (10^-7) to 1 millisecond (10^-3) intervals */

 return ret;
#else
 /* Linux */
 struct timeval tv;

 gettimeofday(&tv, NULL);

 uint64 ret = tv.tv_usec;
 /* Convert from micro seconds (10^-6) to milliseconds (10^-3) */
 ret /= 1000;

 /* Adds the seconds (10^0) after converting them to milliseconds (10^-3) */
 ret += (tv.tv_sec * 1000);

 return ret;
#endif
}
票数 117
EN

Stack Overflow用户

发布于 2009-12-08 01:26:38

我还有另一个使用微秒的工作示例(UNIX、POSIX等)。

代码语言:javascript
复制
    #include <sys/time.h>
    typedef unsigned long long timestamp_t;

    static timestamp_t
    get_timestamp ()
    {
      struct timeval now;
      gettimeofday (&now, NULL);
      return  now.tv_usec + (timestamp_t)now.tv_sec * 1000000;
    }

    ...
    timestamp_t t0 = get_timestamp();
    // Process
    timestamp_t t1 = get_timestamp();

    double secs = (t1 - t0) / 1000000.0L;

下面是我们编写代码的文件:

https://github.com/arhuaco/junkcode/blob/master/emqbit-bench/bench.c

票数 43
EN

Stack Overflow用户

发布于 2013-10-20 05:55:47

这是一个用C++11编写的简单解决方案,它可以提供令人满意的解决方案。

代码语言:javascript
复制
#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_;
};

或在*nix上,用于c++03

代码语言:javascript
复制
#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_;
};

下面是示例用法:

代码语言:javascript
复制
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;
}

来自https://gist.github.com/gongzhitaao/7062087

票数 42
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1861294

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档