2013-07-05 242 views
0

我使用timersub(struct timeval *a, struct timeval *b, struct timeval *res)來按時運行。 我想要做的是,將一個較高的值減去一個較低的值,並得到負值的時間差。C結構timeval timersub()負值爲正

例如:

int    main() 
{ 
    struct timeval  left_operand; 
    struct timeval  right_operand; 
    struct timeval  res; 

    left_operand.tv_sec = 0; 
    left_operand.tv_usec = 0; 
    right_operand.tv_sec = 0; 
    right_operand.tv_usec = 1; 
    timersub(&left_operand, &right_operand, &res); 
    printf("RES : Secondes : %ld\nMicroseconds: %ld\n\n", res.tv_sec, res.tv_usec); 
    return 0; 
} 

輸出是: RES : Secondes : -1 Microseconds: 999999

我想什麼有是:RES : Secondes : 0 Microseconds: 1

是否有人有訣竅的任何想法?我想將結果存儲在結構timeval中。

+0

你爲什麼不只需扳動操作數?那麼你會得到積極的影響。 – 2013-07-05 18:04:32

+0

因爲我實際上是在一個循環中執行這個操作,並且在執行期間值變成負數,所以我必須在操作數中保留這個順序。 – BoilingLime

回答

2

檢查其時間值越大,以確定提供的操作數,其順序爲:

if (left_operand.tv_sec > right_operand.tv_sec) 
    timersub(&left_operand, &right_operand, &res); 
else if (left_operand.tv_sec < right_operand.tv_sec) 
    timersub(&right_operand, &left_operand, &res); 
else // left_operand.tv_sec == right_operand.tv_sec 
{ 
    if (left_operand.tv_usec >= right_operand.tv_usec) 
     timersub(&left_operand, &right_operand, &res); 
    else 
     timersub(&right_operand, &left_operand, &res); 
} 
+0

這很聰明!謝謝。 – BoilingLime