计算程序执行时间

3
我有一个用C语言编写的程序,需要执行一系列其他程序。我需要获取每个程序的执行时间,以便创建这些时间的日志。
我考虑使用system()运行每个程序,但我不知道如何获取执行时间。有没有办法做到这一点?
这些程序非常"快速",因此我需要比秒更精确的测量单位。

你的操作系统是什么? - md5
2个回答

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 APIs,那么您也可以使用 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)

And the best is

#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
clock() 这件事情不应该有效。clock() 应该返回程序使用的 CPU 时间的最佳近似值,它不应该计算由 system() 调用的程序使用的时间(这里没有计算,在 Windows 上可能会有所不同)。 - Daniel Fischer

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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接