[英]Confusion about Timing Measurements
我的任務是實現三個不同的函數get_current_time_seconds1、2和3,然后必須估算各種函數的分辨率。 我怎么估計呢?
您建議使用哪個計時功能? 當我必須使用gcc -O0 -lrt Timing.c -o Timing進行編譯時,編譯器選項-O0 -lrt是什么意思?
#define BILLION 1000000000L
#define LIMIT_I 1000
#define LIMIT_J 1000
double get_current_time_seconds1()
{
/* Get current time using gettimeofday */
time_t t = time(NULL);
struct tm *tm = localtime(&t);
printf("%s\n", asctime(tm));
return (double) tm;
}
double get_current_time_seconds2()
{
struct timespec start,stop;
clock_gettime(CLOCK_REALTIME, &start);
clock_gettime(CLOCK_REALTIME, &stop);
double x = (stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec);
printf("%lf\n", x);
return (double) x;
}
double get_current_time_seconds3()
{
uint64_t diff;
struct timespec start, end;
clock_gettime(CLOCK_MONOTONIC, &start);
sleep(5);
clock_gettime(CLOCK_MONOTONIC, &end);
diff = BILLION * (end.tv_sec - start.tv_sec) + end.tv_nsec - start.tv_nsec;
printf("elapsed time = %llu nanoseconds\n", (long long unsigned int)diff);
return (double) diff;
}
我怎么估計呢? 您建議使用哪個計時功能?
如果要獲取各種計時元素的分辨率(精度),則可以使用clock_getres
函數,傳入各種CLOCK_
id類型,例如:
#include <stdio.h>
#include <time.h>
static void printres(clockid_t id)
{
struct timespec ts;
int rc = clock_getres(id, &ts);
printf("clock id: %d\n", (unsigned int)id);
if (rc != 0) {
printf("Error: %d\n", rc);
return;
}
printf("tv_sec = %lu\ntv_nsec = %lu\n", ts.tv_sec, ts.tv_nsec);
}
int main(int argc, char** argv)
{
printres(CLOCK_REALTIME);
printres(CLOCK_MONOTONIC);
printres(CLOCK_PROCESS_CPUTIME_ID);
printres(CLOCK_THREAD_CPUTIME_ID);
return 0;
}
在我的系統, tv_nsec
為所有,但CLOCK_THREAD_CPUTIME_ID
是1000
,對於CLOCK_THREAD_CPUTIME_ID
的價值tv_nsec
為1
,這意味着對於其他類型的時鍾精度為1毫秒(1000納秒),而精度CLOCK_THREAD_CPUTIME_ID
是1納秒。
對於第一個調用localtime
的函數,其精度為1秒,因為該函數以秒為單位計算Unix時期的時間。
當我必須使用gcc -O0 -lrt Timing.c -o Timing進行編譯時,編譯器選項-O0 -lrt是什么意思?
對於gcc
和clang
等某些編譯器,選項-O
表示在將代碼編譯到指定級別時優化代碼,因此-O0
表示根本不優化代碼,這在調試代碼時通常很有用。
-l
選項表示要針對指定的庫進行編譯,因此-lrt
表示要使用rt
庫或“實時庫”進行編譯; 在某些系統上這是必需的,因為可以在該庫中定義CLOCK_REALTIME
。
希望能對您有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.