Measure execution time in C (on Windows)

2020-02-07 04:00发布

Is there a better function or way to measure time than clock() function on Windows? I have a short operation and when I try clock() or gettickcount() it says it took 0.0 seconds. I need a way to measure it by miliseconds or nanoseconds.

2条回答
混吃等死
2楼-- · 2020-02-07 04:24

You can use QueryPerformanceCounter and QueryPerformanceFrequency :

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

int main(void)
{
    LARGE_INTEGER frequency;
    LARGE_INTEGER start;
    LARGE_INTEGER end;
    double interval;

    QueryPerformanceFrequency(&frequency);
    QueryPerformanceCounter(&start);

    // code to be measured

    QueryPerformanceCounter(&end);
    interval = (double) (end.QuadPart - start.QuadPart) / frequency.QuadPart;

    printf("%f\n", interval);

    return 0;
}
查看更多
我命由我不由天
3楼-- · 2020-02-07 04:30

You can use QueryPerformanceCounter combined with QueryPerformanceFrequency to get nanosecond precision.

查看更多
登录 后发表回答