web-dev-qa-db-ja.com

Cプログラムの経過時間をミリ秒で計算する

プログラムの一部の実行にかかった時間をミリ秒単位で計算したい。オンラインで探していましたが、このトピックに関する情報はあまりありません。これを行う方法を知っている人はいますか?

23
user69514

答える最良の方法は例です:

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

別のオプション(少なくとも一部のUNIXでは) clock_gettime および関連する関数です。これらは、さまざまなリアルタイムクロックへのアクセスを可能にし、より高い解像度のクロックの1つを選択し、不要な解像度を捨てることができます。

5
Pete Kirkham

gettimeofday 関数は、マイクロ秒の精度で時間を返します(もちろん、プラットフォームがそれをサポートできる場合)。

Gettimeofday()関数は、エポック以降の秒とマイクロ秒で表される現在の時刻を取得し、tpが指すtimeval構造体に格納します。システムクロックの解像度は指定されていません。

3
Dirk

Cライブラリには、システム時間を取得する機能があります。開始時間と停止時間をキャプチャした後、経過時間を計算できます。

この関数はgettimeofday()と呼ばれ、manページを参照して、含める内容と使用方法を確認できます。

2
gbarry

Windowsでは、これを行うことができます。

DWORD dwTickCount = GetTickCount();

// Perform some things.

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

最も一般的でエレガントなソリューションではありませんが、必要なときにすばやく簡単に使用できます。

0
Edan Maor