读书人

clock()计算程序运行时间的函数求解

发布时间: 2012-08-21 13:00:21 作者: rapoo

clock()计算程序运行时间的函数求解!~
#include<stdio.h>
#include<time.h>
unsigned __int64 fun(unsigned __int64 x,int n) //求x^n
{
unsigned __int64 pw=1;
while(n)
{
if(n&1)
pw*=x;
x*=x;
n>>=1;
}
return pw;
}
int main()
{
unsigned __int64 x;
int n;
printf("输入64位的x,和32位的n\n");
while(scanf("%I64u%d",&x,&n)==2)
{
printf("输出x^n:\n");
printf("%I64u\n",fun(x,n));
printf("time used=%.2lf\n",(double)clock()/CLOCKS_PER_SEC);
}
}
位什么每次运行所计算出来的时间都不一样呢?百度也百度不到。。。各种找不到,所以请求给位大虾帮我解答!

[解决办法]
可以的:

C/C++ code
#include <stdio.h>#include <stdlib.h>#include <time.h>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() )      ;} 

读书人网 >C语言

热点推荐