计算程序执行时间

时间:2013-03-05 17:00:47

标签: c windows

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

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

程序“快速”,所以我需要比秒更精确。

2 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分: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;