• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wchenfeng

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

(2种)编写一个程序,对于给定的正整数n,求1+2+…+n,采用逐个累加和n(n+1)/2两个解法。对于相同的n,给出这两种解法的求和结果和求解时间

 clock计算的是程序占用cpu的时间,cpu性拿好,程序越简洁,同时运行软件少,运行结果越快。

clock_t start, stop; //clock_t为clock()函数返回的变量类型

  1. 紧接将把返回值赋值给start,stop;

  2. 为了使变量类型一致,需要声明clock_t型变量start,stop;

start = clock(); //开始计时 .返回从main函数开始执行到执行到此的时间

stop = clock(); //停止计时 .返回从main函数开始执行到执行到此的时间

duration=(double)(stop-start)/CLK_TCK; //CLK_TCK为clock()函数的时间单位,即时钟打点

CLK_TCK是机器时钟每秒所走的时钟打点数

方法1

单个数据,一次测试。

#include "stdio.h"
#include "time.h"
#include "math.h"
clock_t start,stop;
double duration;
double duration;
int i;
double f1(int n)
{
	int i,sum=0;
	for(i=1;i<=n;i++)
		sum+=i;
	return sum;
}
double f2(int n)
{
	return (n*(n+1))/2;
}
 
int main()
{
  int n;
  printf("输入一个正整数n:");
  scanf("%d",&n);
  start=clock(); f1(n);
  stop=clock();
  duration=(double)(stop-start)/CLK_TCK;
  printf("ticks1=%f\n",(double)(stop-start));
  printf("duration1=%6.2e\n",duration);
  printf("求和结果为%.0f\n",f1(n));
 
  start=clock(); f2(n);
  stop=clock();
  duration=(double)(stop-start)/CLK_TCK;
  printf("ticks2=%f\n",(double)(stop-start));
  printf("duration2=%6.2e\n",duration);
  printf("求和结果为%.0f\n",f2(n));
  return 0;
}

 输出

 

 输入

因为是一次数据时间测试,所以需要比较大的数进行测试,才会有时间差距

99999999

方法二

单个数据,多次测试。

#include "stdio.h"
#include "time.h"
#include "math.h"
#define MAXK 1e7
clock_t start,stop;
double duration;
double duration;
int i;
double f1(int n)
{
	int i,sum=0;
	for(i=1;i<=n;i++)
		sum+=i;
	return sum;
}
double f2(int n)
{
	return (n*(n+1))/2;
}
 
int main()
{
  int n;
  printf("输入一个正整数n:");
  scanf("%d",&n);
  start=clock(); for(i=0;i<=MAXK;i++)f1(n);
  stop=clock();
  duration=(double)(stop-start)/CLK_TCK/MAXK;
  printf("ticks1=%f\n",(double)(stop-start));
  printf("duration1=%6.2e\n",duration);
  printf("求和结果为%.0f\n",f1(n));
 
  start=clock(); for(i=0;i<=MAXK;i++)f2(n);
  stop=clock();
  duration=(double)(stop-start)/CLK_TCK/MAXK;
  printf("ticks2=%f\n",(double)(stop-start));
  printf("duration2=%6.2e\n",duration);
  printf("求和结果为%.0f\n",f2(n));
  return 0;
}

输出

输入 

因为是多次测试,所以不用太大的数据就能测出差距

100

posted on 2022-04-12 20:02  王陈锋  阅读(299)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3