時間計測

時間計測(list_31.c)
//-----------------------------------------------------------------
// list_31.c
//   CPUの稼動状況から処理にかかる実行時間を計測
//   →1秒間当たりのクロック数の取得
//-----------------------------------------------------------------
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>

//-----------------------------------------------------------------
double calc_cps();
inline unsigned long long int RDTSC(void);
//-----------------------------------------------------------------

int main(void)
{
    int count=0;
    double cpers=0;
    clock_t t1,t2;
    // 計測の初期化
    cpers = calc_cps();
    // 時間計測テスト
    count = 0;
    t1 = clock(); /* 開始 */
    // 時間を計測する処理
    while(1){ count++; if(count == 100000000) break; }
    t2 = clock(); /* 終了 */
    // CLOCKS_PER_SEC:/usr/include/time.h に定義による処理時間
    printf("TIMES: time of loop = %d clock, %lg[sec]\n",
           t2-t1,(double)(t2-t1)/CLOCKS_PER_SEC);
    // 計算した cpers による処理時間
    printf("RDTSC: time of loop = %d clock, %lg[sec]\n",
           t2-t1,(double)((t2-t1)/cpers));
    return 0;
}

// 計測の初期化
double calc_cps()
{
    struct timeval tv1,tv2;
    unsigned long long tsc1,tsc2;
    gettimeofday(&tv2,NULL); tsc2=RDTSC();
    usleep(250);
    gettimeofday(&tv1,NULL); tsc1=RDTSC();
    return (double)(tsc1-tsc2) /
        ((tv1.tv_sec-tv2.tv_sec)*1000000+(tv1.tv_usec-tv2.tv_usec));
        
}
// read Pentium cycle counter
inline unsigned long long int RDTSC(void)
{
    unsigned int h,l;
    __asm__(".byte 0x0f,0x31":"=a" (l),"=d" (h));
    return ((unsigned long long int)h<<32)|l;
}

result
TIMES: time of loop = 500 clock, 0.5[sec]
 RDTSC: time of loop = 500 clock, 0.454782[sec]

inserted by FC2 system