计算 C 程序中耗时(以毫秒为单位)

标签 c unix time system timer

我想计算执行我的程序的某些部分所花费的时间(以毫秒为单位)。我一直在网上寻找,但关于这个主题的信息不多。你们有人知道怎么做吗?

最佳答案

最好的回答方式是举个例子:

#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

/* Return 1 if the difference is negative, otherwise 0.  */
int timeval_subtract(struct timeval *result, struct timeval *t2, struct timeval *t1)
{
    long int diff = (t2->tv_usec + 1000000 * t2->tv_sec) - (t1->tv_usec + 1000000 * t1->tv_sec);
    result->tv_sec = diff / 1000000;
    result->tv_usec = diff % 1000000;

    return (diff<0);
}

void timeval_print(struct timeval *tv)
{
    char buffer[30];
    time_t curtime;

    printf("%ld.%06ld", tv->tv_sec, tv->tv_usec);
    curtime = tv->tv_sec;
    strftime(buffer, 30, "%m-%d-%Y  %T", localtime(&curtime));
    printf(" = %s.%06ld\n", buffer, tv->tv_usec);
}

int main()
{
    struct timeval tvBegin, tvEnd, tvDiff;

    // begin
    gettimeofday(&tvBegin, NULL);
    timeval_print(&tvBegin);

    // lengthy operation
    int i,j;
    for(i=0;i<999999L;++i) {
        j=sqrt(i);
    }

    //end
    gettimeofday(&tvEnd, NULL);
    timeval_print(&tvEnd);

    // diff
    timeval_subtract(&tvDiff, &tvEnd, &tvBegin);
    printf("%ld.%06ld\n", tvDiff.tv_sec, tvDiff.tv_usec);

    return 0;
}

关于计算 C 程序中耗时(以毫秒为单位),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1468596/

相关文章:

c - System V 共享内存的段错误

c - 在Windows中使用C在两个线程之间共享缓冲区的方法有哪些?

c# - 动画 GIF 帧速率似乎低于预期

python - 从 VIM 中执行 Python 代码时如何抑制警告

c - 在客户端-服务器应用程序 (UDP) 中创建并发服务器时出现错误的文件描述符错误

android - 如何获取应用所在的本地时间。正在运行,与设备时间无关?

date - SAS 按日期和时间合并

c++ - 查找 zlib 压缩流的结尾

c - 卡在等待输入上的并行流程场景实现

unix - 将 printf 输出分配给 awk 命令中的变量