2011-12-29 61 views
1

我想減去兩個gettimeofday實例,並以毫秒爲單位顯示答案。如何減去兩個gettimeofday實例?

的理念是:

static struct timeval tv; 
    gettimeofday(&tv, NULL); 

    static struct timeval tv2; 
    gettimeofday(&tv2, NULL); 

    static struct timeval tv3=tv2-tv; 

,然後再轉換 'TV3' 成毫秒的分辨率。

+0

難道你不知道自己? :按字段減去字段,如果其「tv_usec」爲負,則將結果標準化! – 2011-12-29 13:55:06

+0

我認爲有一個更好的方法,而不是使用'如果'的說法。 – user1106106 2011-12-29 13:56:26

回答

6

您可以使用glibc提供的timersub()函數,然後將結果轉換爲毫秒(注意當執行此操作時溢出)。

+0

爲什麼會出現溢出? – user1106106 2011-12-29 14:24:57

+0

@ user1106106:如果您正在減去的兩個值恰好比「XXX_MAX」間隔更遠,那麼轉換爲毫秒的結果顯然不適合單個變量「xxx」。 – janneb 2011-12-29 14:28:05

3

這裏是如何做手工(因爲timersub不在別處提供的標準功能)

struct timeval tv; 
gettimeofday(&tv, NULL); 
// ... 
struct timeval tv2; 
gettimeofday(&tv2, NULL); 

int microseconds = (tv2.tv_sec - tv.tv_sec) * 1000000 + ((int)tv2.tv_usec - (int)tv.tv_usec); 
int milliseconds = microseconds/1000; 
struct timeval tv3; 
tv3.tv_sec = microseconds/1000000; 
tv3.tv_usec = microseconds%1000000; 

(你必須留意溢出,這使事情變得更糟)

目前版本的C++提供了更好的選項,但:

#include <chrono> // new time utilities 

// new type alias syntax 
using Clock = std::chrono::high_resolution_clock; 
// the above is the same as "typedef std::chrono::high_resolution_clock Clock;" 
// but easier to read and the syntax supports being templated 
using Time_point = Clock::time_point; 

Time_point tp = Clock::now(); 
// ... 
Time_point tp2 = Clock::now(); 

using std::chrono::milliseconds; 
using std::chrono::duration_cast; 
std::cout << duration_cast<milliseconds>(tp2 - tp).count() << '\n'; 
+0

woops。你是對的。我正在把它和tm結構混在一起。我會刪除我的評論。 – Octopus 2013-10-17 22:46:39