C++时间函数总结(含思维导图)

一,时间函数知识点总结

二,计算程序运行时间的代码实例(本人课堂实例)

#include <iostream>
#include<ctime> //时间头文件

using namespace std;

int main()
{
    const int Count1 = 10; //声明常量
    const int Count2 = 1000000;//声明常量
    const int Count3 = 1000;//声明常量
    int i,j; //声明变量
   float sum = 0.0;
    time_t start_time, finish_time; //声明时间变量
    clock_t time_req; //定义一个保存时间的变量

    for(i=0;i<Count1; i++) //循环1
        sum+=1.0/Count1; //求和1
    cout << "The sum of the for - loop(COUNT=10) is : " <<sum << endl<<endl; //输出第一个求和结果

    sum=0.0;
    for(i=0;i< Count2;i++) //循环2
        sum+=1.0/Count2; //求和2
    cout<< "The sum of the for -loop(COUNT=1000000) is : " << sum << endl<<endl; //输出第二个求和结果

    time_req = clock();//对从开始到当前计时
    time(&start_time);//当前时间(开始时间)

    sum = 0.0;
    for(i=0; i<Count3; i++)//循环
        for(j=0; j<Count3;j++)
        sum+=(1.0/Count3)*(1.0/Count3);
    cout<< "The sum of the for-loop(COUNT=1000*1000)  is : "<<sum<<endl;
    time(&finish_time); //当前时间与1970.01.01时间差(秒)

    cout << " Time required(time) = " << difftime(finish_time, start_time) << "seconds"<<endl;//求时间差(即执行循环所需时间)
    time_req = clock() - time_req;//运行的时间
    cout<< "Time required(clock) = " << time_req << " clocks" <<endl;//输出循环运行时间,单位毫秒
    cout<< "Time required(clock) = " << (float)time_req/CLOCKS_PER_SEC << "seconds" <<endl <<endl;//输出循环行时间,CLOCKS_PER_SEC表示一秒钟会有多少个时钟计时单位

    time_req = clock();//对从开始到当前计时
    sum = 0.0;
    for(i=0; i<Count2; i++)//循环
        for(j=0; j<Count3; j++)
            sum+= (1.0/Count2)*(1.0/Count3);//求和

    cout<< "The sum of the for -loop(COUNT=1000000*1000) is  : " <<sum <<endl;//输出循环求和结果
    time(&finish_time);//完成的系统时间

    cout << "Time required(time) = " << difftime(finish_time, start_time) << "seconds" <<endl;//输出执行时间
    time_req =clock() - time_req;//运行时间
    cout<< "Time required(clock) = " << time_req << "clocks" <<endl;//输出运行时间,单位毫秒
    cout<< "Time required(clock) = " << (float) time_req/CLOCKS_PER_SEC << "seconds" <<endl;//输出循环运行时间,单位秒

    return 0;
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值