【问题标题】:How to write a macro which gets runtime of a function?如何编写一个获取函数运行时的宏?
【发布时间】:2013-12-29 02:19:14
【问题描述】:

假设我们想知道函数A运行了多长时间,我们可以这样写代码

    struct timeval tpstart,tpend;  
    gettimeofday(&tpstart,NULL); 
    A(); 
    gettimeofday(&tpend,NULL); 
    float timeuse= tpend.tv_sec-tpstart.tv_sec + (tpend.tv_usec-tpstart.tv_usec) / 1000000; 
    printf("Used Time:%f\n",timeuse); 

但是我怎样才能将它封装成一个宏,比如 Runtime(A),也许,Runtime(A, B, ...),有时几个函数一起运行。

【问题讨论】:

  • gettimeofday 不是标准 C 并且也被 POSIX 声明为已过时,请考虑使用来自 POSIX 的 clock_gettime 或来自 C11 的 timespec_get
  • 好吧,这是我google导出的一段代码,之前没用过

标签: c macros posix timeval


【解决方案1】:

如果你不关心函数的返回值,生活很简单:

#define Runtime(x)  do { \
    struct timeval tpstart,tpend;  \
    gettimeofday(&tpstart,NULL);   \
    x; \
    gettimeofday(&tpend,NULL); \
    float timeuse= tpend.tv_sec-tpstart.tv_sec + (float)(tpend.tv_usec-tpstart.tv_usec) / 1000000; \
    printf("Used Time:%f\n",timeuse); \
} while(0)

Runtime( A() );
Runtime( A() ; B() );

【讨论】:

  • 您甚至可以通过#x ": Used Time: %f"获得更多信息。
  • 但是当使用 Runtime(cudaKernel>>());它失败了
  • @stonestrong,您似乎在使用 CUDA?请注意,CUDA 不是 C 而是 C++。预处理器很容易被具有不同语法规则的 C++ 混淆。这里特别是 1,1 中的逗号被预处理器解释为宏参数的分隔。为了应对这种情况,将#define 更改为Runtime(...),三个点,并使用__VA_ARGS__,前后两个下划线,代替x
  • @JensGustedt,额外的一对括号也有帮助 - Runtime((cudaKernel<<<1,1>>>())); - 这样宏就知道它只是一个参数。但是你的宏变体确实更有用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-27
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
相关资源
最近更新 更多