c - 使用类函数宏测量 C 中函数调用的执行时间

标签 c macros execution-time

使用标准库函数clock()是测量C中函数调用的执行时间的几种方法之一。因此,例如,比较两个函数的执行时间(具有不同的原型(prototype))可以按如下方式完成:

#include <stdio.h>
#include <time.h>

int f(int n) { return n < 3 ? 1 : f(n-1) + f(n-2); }

int g(int n, int a, int b) { return n < 3 ? b : g(n-1, b, a+b); }

int main(void) {
    double start, elapsed1, elapsed2;
    printf("n  f   g\n");
    for(int n = 30; n <= 40; n++) {
        start = (double) clock();
        f(n); 
        elapsed1 = (clock() - start) / CLOCKS_PER_SEC;
        start = (double) clock();
        g(n, 1, 1);
        elapsed2 = ((double) clock() - start) / CLOCKS_PER_SEC;
        printf("%d %.1f %.1f\n", n, elapsed1, elapsed2);
    }
    return 0;
}

为了使这段代码更加简洁,我们可以定义一个类似函数的宏(因为C中没有“通用函数”指针):

#include <stdio.h>
#include <time.h>

double START, ELAPSED;

#define CPUTIME(FCALL) (START = (double) clock(), FCALL, ELAPSED = ((double) clock() - START) / CLOCKS_PER_SEC)

int f(int n) { return n < 3 ? 1 : f(n-1) + f(n-2); }

int g(int n, int a, int b) { return n < 3 ? b : g(n-1,b,a+b); }

int main(void) {
    printf("n  f   g\n");
    for(int n = 30; n <= 40; n++) 
        printf("%d %.1f %.1f\n", n, CPUTIME(f(n)), CPUTIME(g(n, 1, 1)) );
    return 0;
}

问题:有没有办法使变量 START 和 ELAPSED 成为宏定义的局部变量,以便宏仍然可以作为非 void“函数”调用?有没有更好的方法让代码更简洁,而不需要使用宏定义?

最佳答案

您可以使用非标准语句表达式 C 扩展 (至少在 clang、gcc 和tinycc 中可用)。

#include <stdio.h>
#include <time.h>

#define CPUTIME(FCALL) ({ double START = clock(); FCALL; ((double) clock() - START) / CLOCKS_PER_SEC; })

int f(int n) { return n < 3 ? 1 : f(n-1) + f(n-2); }

int g(int n, int a, int b) { return n < 3 ? b : g(n-1,b,a+b); }

int main(void) {
    printf("n  f   g\n");
    for(int n = 30; n <= 40; n++) 
        printf("%d %.1f %.1f\n", n, CPUTIME(f(n)), CPUTIME(g(n, 1, 1)) );
    return 0;
}

它是一个带括号的 block ,其计算结果为其中最后一个语句的计算结果。

我认为标准 C 中没有通用的解决方案可以满足您的 API 限制。如果您追求仅标准 C 线程安全和/或稍微更好的代码生成,您可以使用原始解决方案并在调用宏的 block 内本地(重新)声明变量。

关于c - 使用类函数宏测量 C 中函数调用的执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76028547/

相关文章:

c++ - 线程 : How to calculate precisely the execution time of an algorithm (duration of function) in C or C++?

c - 为什么以下在单链表末尾插入节点的代码不起作用?

c++ - 我的任务是将 lwIP 从 C 转换为 C++

c - C POSIX进程管道/套接字通信练习第二个进程被卡住

c - 寻找表生成宏惯用语的良好解释

assembly - Tasm 宏默认值

c++ - C++中执行时间显示 : cin/scanf/getchar_unlocked()

c - 即使我使用它, make 也会告诉我使用 std c99

c++ - g++ 命令行宏定义字节流

php - 出于安全原因,set_time_limit() 已被禁用