C语言clock()测试函数运行时间

运行环境:
win10家庭版 64位
MinGW.org GCC-6.3.0-1

以下英文解释引自man page: man 3 clock

DESCRIPTION
The clock() function returns an approximation of processor time used by the program.

RETURN VALUE
The value returned is the CPU time used so far as a clock_t; to get the number of seconds used, divide by
CLOCKS_PER_SEC. If the processor time used is not available or its value cannot be represented, the function
returns the value (clock_t) -1.

clock()函数返回 程序占用的处理器时间粗略值, 要想获得实际的秒数, 最后要除以CLOCKS_PER_SEC

这个CLOCKS_PER_SEC是什么东西? 在time.h中有如下定义:

/* Number of clock ticks per second. A clock tick is the unit by which
 * processor time is measured and is returned by 'clock'.
 */
#define CLOCKS_PER_SEC	((clock_t)(1000))
#define CLK_TCK 	CLOCKS_PER_SEC

当然这个CLOCKS_PER_SEC不一定是1000, 各个系统可能不太一样, 所以还是使用常量.
CLK_TCK也可以用, 不过已经过时了, 最好是使用CLOCKS_PER_SEC常量.

那如何用它来测试程序执行时间呢?
演示代码:

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

int f1() {
    int i;
    int j;
    int tmp;
    int loopNum = 10000;
    for (i = 0; i < loopNum; i++) {
        for (j = 0; j < loopNum; j++) {
            tmp = i * j;
        }
    }
    return tmp;
}

int main(int argc, char const *argv[])
{
    const int N = 1e2;
    int i = 0;
    clock_t start, end;
    start = clock();
    for (; i < N; i++) {
        f1();
    }
    end = clock();
    printf("time: %f s\n", ((double)(end - start)) / CLOCKS_PER_SEC / N);
    return 0;
}

在我的电脑上运行结果为:

time: 0.222540 s
也就是说, 函数f1的平均运行时间约为0.22秒.

说明: 可以看到, 上面对f1执行了N次. 因为在大多数情况下, 被测试函数(如当前的f1)可能运行很快, 只运行一次的话由于时间太短, 结果就是0, 所以多跑几次, 再求均值即可.

欢迎补充指正!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值