C时间统计

 

在C中使用时间统计是常用的操作,记录一版如下:

#include <time.h>
#include <stdio.h>
using namespce std;

int main()
{
    clock_t start,finish;
    double duration;
    start = clock();
    dosomething();
    finish = clock();
    duration = (double)(finish-start) / CLOCKS_PER_SEC;
    printf("%lf seconds \n",duration);
}

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else // _WIN32
#include <sys/time.h>
#endif // _WIN32

#ifdef _WIN32
typedef struct timeval
{
    long tv_sec;
    long tv_usec;
} timeval;

int gettimeofday(struct timeval *tp, struct timezone *tzp)
{
    // Note: some broken versions only have 8 trailing zero's, the correct epoch has 9 trailing zero's
    // This magic number is the number of 100 nanosecond intervals since January 1, 1601 (UTC)
    // until 00:00:00 January 1, 1970
    static const uint64_t EPOCH = ((uint64_t)116444736000000000ULL);

    SYSTEMTIME system_time;
    FILETIME file_time;
    uint64_t time;

    GetSystemTime(&system_time);
    SystemTimeToFileTime(&system_time, &file_time);
    time = ((uint64_t)file_time.dwLowDateTime);
    time += ((uint64_t)file_time.dwHighDateTime) << 32;

    tp->tv_sec = (long)((time - EPOCH) / 10000000L);
    tp->tv_usec = (long)(system_time.wMilliseconds * 1000);
    return 0;
}
#endif

struct timeval tv_start;

float get_ms(void)
{
  struct timeval tv_end;
  float ms;
  gettimeofday(&tv_end, NULL);
  ms = (tv_end.tv_sec - tv_start.tv_sec) * 1000.0 + (tv_end.tv_usec - tv_start.tv_usec) / 1000.0;
  tv_start = tv_end;
  return ms;
}