3

我有一个 C 语言程序,它必须执行一系列其他程序。我需要获取每个程序的执行时间,以便创建这些时间的日志。

我虽然使用 system() 来运行每个程序,但我不知道如何获得执行时间。有没有办法做到这一点?

这些程序是“快速”的,所以我需要比秒更高的精度。

4

2 回答 2

4

你至少有 4 种方法可以做到这一点。

(1)

一个起点:

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

 int main ( void )
 {
    clock_t start = clock();

    system("Test.exe");

    printf ("%f\n seconds", ((double)clock() - start) / CLOCKS_PER_SEC);
    return 0;
 }

(2)

如果您在 Windows 中并且可以访问 Window API,您也可以使用GetTickCount()

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


 int main ( void )
 {
    DWORD t1 = GetTickCount();

    system("Test.exe");

    DWORD t2 = GetTickCount();

    printf ("%i\n milisecs", t2-t1);
    return 0;
 }

(3)

最好的是

#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);

    system("calc.exe");

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

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

    return 0;
}

(4)

问题被标记为C但为了完整起见,我想添加C++11功能:

int main()
{
  auto t1 = std::chrono::high_resolution_clock::now();

  system("calc.exe");

  auto t2 = std::chrono::high_resolution_clock::now();
  auto x = std::chrono::duration_cast<std::chrono::nanoseconds>(t2-t1).count();

  cout << x << endl;
}
于 2013-03-05T17:05:34.670 回答
0
    start = clock();  // get number of ticks before loop
     /*
      Your Program
    */

    stop  = clock();  // get number of ticks after loop
    duration = ( double ) (stop - start ) / CLOCKS_PER_SEC;
于 2013-03-05T17:07:45.803 回答