在C程序中以毫秒计算经过的时间

25

我想计算程序执行某部分所花费的毫秒数。我在网上搜索,但这个话题的信息不多。你们中有谁知道如何做到这一点吗?


重新标记以符合惯例。 - dmckee --- ex-moderator kitten
1
嗯...一周前我回答过这个问题:https://dev59.com/P3M_5IYBdhLWcg3wSBAU#1445808 - Christoph
5个回答

34

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

#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;
}

5

另一种选择(至少在某些UNIX系统上)是使用clock_gettime和相关函数。这些函数允许访问各种实时时钟,并且您可以选择其中一个更高分辨率的时钟并且舍去您不需要的分辨率。


1
特别是,如果您运行的系统支持CLOCK_MONOTONIC时钟(sysconf(_SC_MONOTONIC_CLOCK) > 0)。 - caf

3

gettimeofday函数返回带有微秒精度的时间(当然,如果平台支持的话):

gettimeofday()函数将获取当前时间,以自纪元以来的秒和微秒表示,并将其存储在指向timeval结构的指针tp中。系统时钟的分辨率未指定。

注:自纪元(Epoch)是指计算机所采用的起始时间点。

1
gettimeofday 不适合用于测量两个事件之间经过的时间,因为系统时钟可能会在事件之间发生改变(例如通过 NTP 更新或管理员操作)。尽管如此,有时它仍然是最好的选择。 - caf

2

C语言库有一个函数可以让您获取系统时间。在捕获开始和结束时间后,您可以计算经过的时间。

该函数称为gettimeofday(),您可以查看手册了解应包含哪些内容以及如何使用它。


0

在Windows上,你可以这样做:

DWORD dwTickCount = GetTickCount();

// Perform some things.

printf("Code took: %dms\n", GetTickCount() - dwTickCount);

这不是最通用/优雅的解决方案,但在需要快速解决问题时非常方便。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接