C++实现计算程序运行时间

2025-01-31 09:59:44
推荐回答(3个)
回答1:

用高精度计时器
#include
#include
using namespace std ;

int main(void)
{
LARGE_INTEGER BegainTime ;
LARGE_INTEGER EndTime ;
LARGE_INTEGER Frequency ;
QueryPerformanceFrequency(&Frequency);
QueryPerformanceCounter(&BegainTime) ;
//要测试的代码放在这里
QueryPerformanceCounter(&EndTime) ;
cout << ( EndTime.QuadPart - BegainTime.QuadPart )*1000 / Frequency.QuadPart ;

system("pause") ;
return 0 ;
}

回答2:

/* CLOCK.C: This example prompts for how long
* the program is to run and then continuously
* displays the elapsed time for that period.
*/

#include
#include
#include

void sleep( clock_t wait );

void main( void )
{
long i = 600000L;
clock_t start, finish;
double duration;

/* Delay for a specified time. */
printf( "Delay for three seconds\n" );
sleep( (clock_t)3 * CLOCKS_PER_SEC );
printf( "Done!\n" );

/* Measure the duration of an event. */
printf( "Time to do %ld empty loops is ", i );
start = clock();
while( i-- )
;
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
printf( "%2.1f seconds\n", duration );
}

/* Pauses for a specified number of milliseconds. */
void sleep( clock_t wait )
{
clock_t goal;
goal = wait + clock();
while( goal > clock() )
;
}

Output

Delay for three seconds
Done!
Time to do 600000 empty loops is 0.1 seconds

回答3:

int t1,t2;
SYSTEMTIME ctime;
GetLocalTime(&ctime);
t1=ctime.wMilliseconds;
for (int j=0;j<10000;j++)
for (int i=0;i<10000;i++)
i=i;
GetLocalTime(&ctime);
t2=ctime.wMilliseconds;
printf("%d\n",t2-t1);

毫秒级的