簡體   English   中英

在POSIX中以毫秒和微秒的精度來測量經過時間的最佳方法是什么?

[英]What's the best way of measuring elapsing time in POSIX with the milliseconds and microsecond accuracy?

我有一些函數foo ,我想以以下格式獲取它的經過時間,例如:

1 seconds 101 milliseeconds 31 microseconds

要么

0 seconds 91 milliseeconds 101 microseconds

現在,我使用以下代碼解決此問題:

static struct timeval t1, t2;
gettimeofday(&t1, NULL);
foo();
gettimeofday(&t2, NULL);
unsigned long long t = 1000 * (t2.tv_sec - t1.tv_sec) + (t2.tv_usec - t1.tv_usec) / 1000;
printf("elapsed time %llu ms\n", t);

我從網上獲得了這個公式,但並不完全理解它。 為什么我應該將1000乘以(t2.tv_sec - t1.tv_sec) 在POSIX中以毫秒和微秒的精度來測量經過時間的最佳方法是什么?

測量時間是一個復雜的問題。 通常,最好的方法是使用clock_gettime()

它支持幾個具有不同特性的時鍾。 檢查鏈接以獲取更多信息。

tv_usec字段是經過的時間(以微秒為單位), tv_sec是經過的時間(以秒為單位)。

因此,將tv_sec字段乘以1000,可以將秒轉換為毫秒,而將tv_usec除以1000,則可以將微秒轉換為毫秒。

我本來建議使用clock_gettime()但在我添加它之前, Let_Me_Be發布了一個提示,建議這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM