秒級精度用 time() 即可;毫秒/微秒級需用 gettimeofday()。
提供秒與微秒雙重精度,使用 struct timeval 結構:
struct timeval {
long tv_sec; // 秒
long tv_usec; // 微秒
};
#include
#include
#include
#include
void function() {
unsigned int i, j;
double y;
for (i = 0; i < 10000; i++)
for (j = 0; j < 10000; j++)
y = sin((double)i);
}
int main(int argc, char **argv) {
struct timeval tpstart, tpend;
float timeuse;
gettimeofday(&tpstart, NULL);
function();
gettimeofday(&tpend, NULL);
timeuse = 1000000 * (tpend.tv_sec - tpstart.tv_sec) + tpend.tv_usec - tpstart.tv_usec;
timeuse /= 1000000;
printf("Used Time: %f 秒\n", timeuse);
exit(0);
}
記錄開始/結束時間,計算差值(微秒),轉換為秒,得精確執行時間。
gettimeofday() 搭配 struct timeval 是 Linux 微秒級時間測量簡單有效方式,廣泛用於效能測試、延遲分析。