C - 跨平台中毫秒精确定时功能

时间:2013-07-14 12:03:42

标签: c time profiling cross-platform

有没有办法使用跨平台方法在C中获得毫秒精度,准确度(至少在几毫秒内)?

在POSIX系统上

我可以使用sys / time.h,但这不是跨平台的。

stdlib time()函数仅提供二级精度

3 个答案:

答案 0 :(得分:4)

我还没有找到一个跨平台的解决方案,用C来衡量时间本身。但是,我所做的是为Unix和Windows使用几乎相同的功能。我创建了这个gist因为我每次都要重新查看它。简而言之:

的Unix

#include <time.h>

long diff_micro(struct timespec *start, struct timespec *end)
{
    /* us */
    return ((end->tv_sec * (1000000)) + (end->tv_nsec / 1000)) -
        ((start->tv_sec * 1000000) + (start->tv_nsec / 1000));
}

long diff_milli(struct timespec *start, struct timespec *end)
{
    /* ms */
    return ((end->tv_sec * 1000) + (end->tv_nsec / 1000000)) -
        ((start->tv_sec * 1000) + (start->tv_nsec / 1000000));
}

int main(int argc, char **argv)
{
    struct timespec start, end;

    clock_gettime(CLOCK_MONOTONIC, &start);

    // Activity to be timed
    sleep(1000);

    clock_gettime(CLOCK_MONOTONIC, &end);

    printf("%ld us\n", diff_micro(&start, &end));
    printf("%ld ms\n", diff_milli(&start, &end));

    return 0;
}

source for Unix solution

的Win32

#include <Windows.h>

long diff_micro(LARGE_INTEGER *start, LARGE_INTEGER *end)
{
    LARGE_INTEGER Frequency, elapsed;

    QueryPerformanceFrequency(&Frequency); 
    elapsed.QuadPart = end->QuadPart - start->QuadPart;

    elapsed.QuadPart *= 1000000;
    elapsed.QuadPart /= Frequency.QuadPart;

    return elapsed.QuadPart;
}

long diff_milli(LARGE_INTEGER *start, LARGE_INTEGER *end)
{
    LARGE_INTEGER Frequency, elapsed;

    QueryPerformanceFrequency(&Frequency); 
    elapsed.QuadPart = end->QuadPart - start->QuadPart;

    elapsed.QuadPart *= 1000;
    elapsed.QuadPart /= Frequency.QuadPart;

    return elapsed.QuadPart;
}

int main(int argc, char **argv)
{
    LARGE_INTEGER StartingTime, EndingTime;

    QueryPerformanceCounter(&StartingTime);

    // Activity to be timed
    Sleep(1000);

    QueryPerformanceCounter(&EndingTime);

    printf("%ld us\n", diff_micro(&StartingTime, &EndingTime));
    printf("%ld ms\n", diff_milli(&StartingTime, &EndingTime));

    return 0;
}

source used for Win32 solution

答案 1 :(得分:0)

您可以尝试这样的事情: -

#include <time.h>
clock_t uptime = clock() / (CLOCKS_PER_SEC / 1000);

请参阅此Link

答案 2 :(得分:0)

最好的方法是使用std::chrono

#include <chrono>

...

auto begin = std::chrono::high_resolution_clock::now();

...

auto end = std::chrono::high_resolution_clock::now();
elapsedTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - begin).count();