最近突然有必要测试C语言中各个函数的运行时间,于是就搜索了一下,发现有4种方法可以达成测算程序运行时间的目的。
它们分别是使用clock, times, gettimeofday, getrusage来实现的。下面就来逐一介绍,并比较它们的优劣点。
系统测试环境:
VirtualBox (Ubuntu 9.10)
gcc version 4.4.1
libc6 2.10.1-0ubuntu16
Core Duo T2500 2GMHz
首先先贴出我测试用的程序吧。
程序做的处理很简单,就是填写一个1024*1024的矩阵。
只要修改第11行的定义值,就可以使用不同的测量方法了。
#include <sys/time.h>
#include <sys/resource.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#define TEST_BY_CLOCK (char)(0x00)
#define TEST_BY_TIMES (char)(0x01)
#define TEST_BY_GETTIMEOFDAY (char)(0x02)
#define TEST_BY_GETRUSAGE (char)(0x03)
#define TEST_METHOD (TEST_BY_GETTIMEOFDAY)
#define COORDINATION_X (int)(1024)
#define COORDINATION_Y (int)(1024)
static int g_Matrix[COORDINATION_X][COORDINATION_Y];
double getTimeval()
{
struct rusage stRusage;
struct timeval stTimeval;
if (TEST_METHOD == TEST_BY_GETTIMEOFDAY) {
gettimeofday(&stTimeval, NULL);
} else if (TEST_METHOD == TEST_BY_GETRUSAGE) {
getrusage(RUSAGE_SELF, &stRusage);
stTimeval = stRusage.ru_utime;
}
return stTimeval.tv_sec + (double)stTimeval.tv_usec*1E-6;
}
int main()
{
int i, j;
int n = 0;
clock_t clockT1, clockT2;
double doubleT1, doubleT2;
if (TEST_METHOD == TEST_BY_CLOCK) {
clockT1 = clock();
} else if (TEST_METHOD == TEST_BY_TIMES) {
times(&clockT1);
} else if (TEST_METHOD == TEST_BY_GETTIMEOFDAY) {
doubleT1 = getTimeval();
} else if (TEST_METHOD == TEST_BY_GETRUSAGE) {
doubleT1 = getTimeval();
}
for (i = 0; i < COORDINATION_X; i++) {
for (j = 0; j < COORDINATION_Y; j++) {
g_Matrix[i][j] = i * j;
}
}
if (TEST_METHOD == TEST_BY_CLOCK) {
clockT2 = clock();
printf("Time result tested by clock = %10.30f\n",
(double)(clockT2 - clockT1)/CLOCKS_PER_SEC);
} else if (TEST_METHOD == TEST_BY_TIMES) {
times(&clockT2);
printf("Time result tested by times = %10.30f\n",
(double)(clockT2 - clockT1)/sysconf(_SC_CLK_TCK));
} else if (TEST_METHOD == TEST_BY_GETTIMEOFDAY) {
doubleT2 = getTimeval();
printf("Time result tested by gettimeofday = %10.30f\n",
(double)(doubleT2 - doubleT1));
} else if (TEST_METHOD == TEST_BY_GETRUSAGE) {
doubleT2 = getTimeval();
printf("Time result tested by getrusage = %10.70f\n",
(double)(doubleT2 - doubleT1));
}
return 0;
}