0

我在我的程序中使用“time.h”来表示从一个点到另一个代码点的执行时间:

    #include <time.h>

    ...

    //clock
    clock_t avvio;
    clock_t fine;

    //start measurement
    avvio = clock();

    .....
    do works
    ....

     //end measurement
    fine = clock()-avvio;

    //conversion in seconds
    double tempoimp = fine / (double)CLOCKS_PER_SEC;

我在这里找到了这段代码,并使用它。有效,但是“经过”的秒数很好 / 1000 ,这假设了一个“硬实时”系统,而我的笔记本不是。

那么,你建议我用什么来衡量一组指令所需的时间,这样我就可以得到程序的执行时间(以秒为单位)?

我需要真正的毫秒......不是时钟周期的划分......

有人可以帮助我吗??

4

1 回答 1

2

您可以使用clock_gettime,它提供了更高分辨率的计时器。

struct timespec t1 = { 0, 0 },
                t2 = { 0, 0 };

if (clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &t1) < 0){
    perror ("Failed to get cpu time");
    return -1;
}

/* test code starts here */

for (int i = 0; i < 200000000; i++); // hefty loop

/* test code ends here */

if (clock_gettime (CLOCK_PROCESS_CPUTIME_ID, &t2) < 0){
     perror ("Failed to get cpu time");
     return -1;
}

printf ("Test code took %d.%d\n",
       (int)(t2.tv_sec - t1.tv_sec),
       (int)(t2.tv_nsec - t1.tv_nsec));

但是时钟周期会更准确地反映代码的执行速度。您无法准确地使用任何时间测量来测量程序速度。这是因为有很多变量可能会影响程序的执行时间

  • 正在运行的其他进程数
  • 您计算机上的可用内存数量
  • 处理器时钟速度的变化

更新(适用于 Windows):

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

int main (){

    LARGE_INTEGER count1, count2, freq;

    if (!QueryPerformanceCount (&count1)){
            perror ("Couldn't get first count");
            return -1;
    }

    for (int i = 0; i < 200000000; i++);

    if (!QueryPerformanceCount (&count2)){
            perror ("Couldn't get second count");
            return -1;
    }

    if(!QueryPerformanceFrequency(&freq)){
        perror ("Couldn't get processor frequency");
        return -1;
    }

    #if ( __WORDSIZE == 64 )
    #pragma message "Performing 64-bit build"

    printf ("The difference is %ll\n", count2.QuadPart - count1.QuadPart);
    printf ("Time (appx): %l\n", (count2.QuadPart - count1.QuadPart) / freq.QuadPart );
    #else 
    #pragma message "Performing 32-bit build"

    /* The code for 32-bit builds here is incomplete. The difference
     * becomes inaccurate after the time has exceeded 32-bits. You can 
     * work out the math to compensate for that, or just start compiling
     * for 64-bit builds. (Google "compile 64 bit visual studio").
     *
     * 
     */

    #endif

    /* A processor frequency can change during a 
     * computationally intensive program. Therefore,
     * the difference in clock ticks (above) is the most
     * accurate way to measure performance.
     */
}
于 2013-06-09T21:32:22.397 回答