测试程序时间(C/C++)

mzf333 2007-12-09 01:02:25
来写我们测试程序时间的代码,精度越高越好.
以下是我提供的一个求质数的程序.看他的运行时间.
//以下是经典的开根号的算法
#include<math.h>
#include <stdio.h>
#define SIZE 1000
void main()
{
int i,n,cnt=0;
printf("%d ", 2); //素数2单独输出
for(n=3; n<=SIZE; n+=2) {
int temp=int(sqrt(n));
for(i=2; i<=temp; i++)
if(n %i == 0)
break; //执行break时为非正常结束循环
if(i>temp)
{
++cnt;
printf("%d ", n);
if(cnt%10==0)
printf("\n");
}//输出一个素数
}
printf("\n");
}

把N改大一点做测试~~答者有分,志在参与.哈哈~~~
...全文
323 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
vsfan 2007-12-10
  • 打赏
  • 举报
回复
有一个办法可以的,使用内嵌的汇编指令RSDTC可以看timestamp
hastings 2007-12-10
  • 打赏
  • 举报
回复
你的电脑主频太高。。。
此种小问题,你的电脑来不及计时。。。
^_^。。。
vsfan 2007-12-10
  • 打赏
  • 举报
回复
inline unsigned __int64 GetCycleTime()
{
__asm _emit 0x0F
__asm _emit 0x31
}

这个是对应的VC6内存汇编函数
调用这个函数的时候相即做RSDTC
调用两次分别保存其值相减即可
更加具体的请看msdn
taodm 2007-12-10
  • 打赏
  • 举报
回复
被测代码循环执行X次,比如1万,1亿,取总时间。
当然,在多任务操作系统下,你怎么做精度都有限。
mzf333 2007-12-10
  • 打赏
  • 举报
回复
N改大了还是可以D,楼上的怎么用?
你做个出来看看
mzf333 2007-12-09
  • 打赏
  • 举报
回复
还有没有更精确D?因为N取太小就会显示0.000000
取小点也能显示的测试程序有没有啊?
tangshuiling 2007-12-09
  • 打赏
  • 举报
回复

#include<math.h>
#include <stdio.h>
#include <time.h>
#define SIZE 1000
void main()
{
int i,n,cnt=0;
clock_t start,end;
start=clock();
printf("%d ", 2); //素数2单独输出
for(n=3; n<=SIZE; n+=2) {
int temp=int(sqrt(n));
for(i=2; i<=temp; i++)
if(n %i == 0)
break; //执行break时为非正常结束循环
if(i>temp)
{
++cnt;
printf("%d ", n);
if(cnt%10==0)
printf("\n");
}//输出一个素数
}
printf("\n");
end=clock();
printf("%lf",(long float)(end-start)/CLK_TCK);
}


mzf333 2007-12-09
  • 打赏
  • 举报
回复
- -!我的意思是把你们做去来的测试程序时间的程序加如我的例子程序,
看运行出来是多少秒,精度如何
zhangyanli 2007-12-09
  • 打赏
  • 举报
回复
以下是从别人那里抄来的:

1.使用CTime类
CString str;
//获取系统时间
CTime tm;
tm=CTime::GetCurrentTime();
str=tm.Format("现在时间是%Y年%m月%d日 %X");
MessageBox(str,NULL,MB_OK);

2: 得到系统时间日期(使用GetLocalTime)

SYSTEMTIME st;
CString strDate,strTime;
GetLocalTime(&st);
strDate.Format("%4d-%2d-%2d",st.wYear,st.wMonth,st.wDay);
strTime.Format("%2d:%2d:%2d",st.wHour,st.wMinute,st.wSecond);

3.使用GetTickCount
//获取程序运行时间
long t1=GetTickCount();//程序段开始前取得系统运行时间(ms)
Sleep(500);
long t2=GetTickCount();();//程序段结束后取得系统运行时间(ms)
str.Format("time:%dms",t2-t1);//前后之差即 程序运行时间
AfxMessageBox(str);
//获取系统运行时间
long t=GetTickCount();

CString str,str1;
str1.Format("系统已运行 %d时",t/3600000);
str=str1;
t%=3600000;
str1.Format("%d分",t/60000);
str+=str1;
t%=60000;
str1.Format("%d秒",t/1000);
str+=str1;
AfxMessageBox(str);
mzf333 2007-12-09
  • 打赏
  • 举报
回复
不是,那个是例子程序.
是做个测试程序测试运行所花费时间的;
yxwsbobo 2007-12-09
  • 打赏
  • 举报
回复
MS没看懂LZ想干嘛 找求素数更好的方法吗

64,637

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧