我有一个用C语言编写的程序,需要执行一系列其他程序。我需要获取每个程序的执行时间,以便创建这些时间的日志。
我考虑使用system()运行每个程序,但我不知道如何获取执行时间。有没有办法做到这一点?
这些程序非常"快速",因此我需要比秒更精确的测量单位。
我考虑使用system()运行每个程序,但我不知道如何获取执行时间。有没有办法做到这一点?
这些程序非常"快速",因此我需要比秒更精确的测量单位。
#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;
}
如果您使用的是 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;
}
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;
}
这个问题被标记为 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;
}
clock()
这件事情不应该有效。clock()
应该返回程序使用的 CPU 时间的最佳近似值,它不应该计算由 system()
调用的程序使用的时间(这里没有计算,在 Windows 上可能会有所不同)。 - Daniel Fischer 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;