共用方式為


difftime, _difftime32, _difftime64

求得兩個時間的差。

語法

double difftime( time_t timeEnd, time_t timeStart );
double _difftime32( __time32_t timeEnd, __time32_t timeStart );
double _difftime64( __time64_t timeEnd, __time64_t timeStart );

參數

timeEnd
結束時間。

timeStart
開始時間。

傳回值

difftime 會傳回從 timeStarttimeEnd 經過的時間 (秒)。 傳回的值是雙精度浮點數。 傳回的值可能是 0,表示有錯誤。

備註

difftime 函式會計算所提供之兩個時間值 timeStarttimeEnd 的差。

所提供的時間值必須符合 time_t 的範圍。 time_t 是 64 位元值。 因此,範圍的結束時間已從 2038 年 1 月 18 日 23:59:59 (UTC) 延長到 3000 年 12 月 31 日 23:59:59。 time_t 的較低範圍仍然是 1970 年 1 月 1 日午夜。

difftime 是評估為 _difftime32_difftime64 的內嵌函式 (取決於是否定義 _USE_32BIT_TIME_T)。 _difftime32 和 _difftime64 可用來直接強制使用特定大小的時間類型。

這些函式會驗證它們的參數。 如果其中一個參數為零或負數,則會叫用不正確參數處理常式,如參數驗證 中所述 。 如果允許繼續執行,這些函式會傳回 0,並將 errno 設定為 EINVAL

根據預設,此函式的全域狀態會限定于應用程式。 若要變更此行為,請參閱 CRT 中的全域狀態。

需求

常式 必要的標頭
difftime <time.h>
_difftime32 <time.h>
_difftime64 <time.h>

如需相容性詳細資訊,請參閱相容性

範例

// crt_difftime.c
// This program calculates the amount of time
// needed to do a floating-point multiply 100 million times.
//

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <float.h>

double RangedRand( float range_min, float range_max)
{
   // Generate random numbers in the half-closed interval
   // [range_min, range_max). In other words,
   // range_min <= random number < range_max
   return ((double)rand() / (RAND_MAX + 1) * (range_max - range_min)
            + range_min);
}

int main( void )
{
   time_t   start, finish;
   long     loop;
   double   result, elapsed_time;
   double   arNums[3];

   // Seed the random-number generator with the current time so that
   // the numbers will be different every time we run.
   srand( (unsigned)time( NULL ) );

   arNums[0] = RangedRand(1, FLT_MAX);
   arNums[1] = RangedRand(1, FLT_MAX);
   arNums[2] = RangedRand(1, FLT_MAX);
   printf( "Using floating point numbers %.5e %.5e %.5e\n", arNums[0], arNums[1], arNums[2] );

   printf( "Multiplying 2 numbers 100 million times...\n" );

   time( &start );
   for( loop = 0; loop < 100000000; loop++ )
      result = arNums[loop%3] * arNums[(loop+1)%3];
   time( &finish );

   elapsed_time = difftime( finish, start );
   printf( "\nProgram takes %6.0f seconds.\n", elapsed_time );
}
Using random floating point numbers 1.04749e+038 2.01482e+038 1.72737e+038
Multiplying 2 floating point numbers 100 million times...
Program takes      3 seconds.

另請參閱

數學和浮點支援
時間管理
time, _time32, _time64