[英]Calculate program execution time
I have a program in C which has to execute a series of another programs. 我在C中有一个程序,它必须执行一系列其他程序。 I need to get the execution time of each of these programs, in order to create a log of these times.
我需要获取每个程序的执行时间,以便创建这些时间的日志。
I though of using system() to run each program, but I don't know how to get the execution time. 我虽然使用system()来运行每个程序,但我不知道如何获得执行时间。 Is there any way to do this?
有没有办法做到这一点?
The programs are "quick", so I need more precision than seconds. 程序是“快速的”,所以我需要比秒更精确。
You have at least 4 ways to do it. 您至少有4种方法可以做到这一点。
A start point: 一个起点:
#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;
}
If you are in Windows and you have access to Window APIs you can use GetTickCount()
too: 如果您在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;
}
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;
}
Question is tagged as C
but for sake of completeness, I want add C++11
feature: 问题被标记为
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;
}
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.