[C++]用变量增长模拟算法运行时间

模拟算法运行所需时间

Description:

Carson write a simple program to solve Fabonaci and Factorial.
But he wants to know how it cost time when different inputs are given.
Now you are invited as an best expert to fix it.
Read main.cpp for details about the functions of

“`
standard input
1 2 3 4 5
6 7 8 9 10

standard output
input: 1, result: 1
input: 2, result: 2
input: 3, result: 2
input: 4, result: 4
input: 5, result: 5
line 0 - 1: 0.050ms
line 1 - 2: 0.050ms
line 2 - 3: 0.150ms
line 3 - 4: 0.250ms
line 4 - 5: 0.450ms
input: 6, result: 720
input: 7, result: 5040
input: 8, result: 40320
input: 9, result: 362880
input: 10, result: 3628800
line 0 - 1: 0.300ms
line 1 - 2: 0.350ms
line 2 - 3: 0.400ms
line 3 - 4: 0.450ms
line 4 - 5: 0.500ms
#Timer_1: 0.950ms
#Timer_2: 2.000ms
“`

test:

#include <iostream>
#include "timer.h"
using std::cin;
using std::cout;
using std::endl;
using std::string;
using namespace TIC_TOC;

// f(n) = 0, n = 1
// f(n) = 1, n = 2
// f(n) = f(n-1) + f(n-2), n > 2
int fabonaci(int n) {
    clock_f();  // it takes 50 clocks (0.050ms)
    if (n == 1) return 0;
    else if (n == 2) return 1;
    else return fabonaci(n-1) + fabonaci(n-2);
}

// f(n) = 1, n = 1
// f(n) = n * f(n-1), n > 1
int factorial(int n) {
    clock_f();
    if (n == 1) return 1;
    return n*factorial(n-1);
}

timer_controller T;  // create a timer_controller
int number[5];  // input for test
int count;  // count the lines(tic -> toc)

void testTicToc(int n, string function) {
    count = 0;
    cin >> number[0] >> number[1] >> number[2]
    >> number[3] >> number[4];
    for (int i = 0; i < 5; i++) {
        T[n].tic_f(count++);  // tic for starting time
        cout << "input: " << number[i] << ", result: ";
        if (function == "fabonaci")
            cout << fabonaci(number[i]) << endl;
        else if (function == "factorial")
            cout << factorial(number[i]) << endl;
        T[n].toc_f(count);  // toc for ending time
    }
    T[n].tictoc(stdout);  // print out the line-time information
}

int main(void) {
    T.create(2);
    testTicToc(0, "fabonaci");
    testTicToc(1, "factorial");
    T.display(stdout);  // print out the total time of each timer
    return 0;
}

My answer:

#include <time.h>
#include <iomanip>
#include <stdio.h>
#include <iostream>
static int _clock = 0;
inline void clock_f() {
    for (int i = 0; i != 50; i++) {
        _clock++;
    }
}
inline double getTime() {
    return 0.001 * _clock;
}

#define MAX_TIMER 5
// namespace TIC_TOC
namespace TIC_TOC {
class timer {
private
:
    double times[5];
public
:
    timer() {
        for (int i = 0; i != 5; i++) {
            times[i] = 0;
        }
    }
    double getAllRdtsc() {
        double totalTime = 0;
        for (int i = 0; i != 5; i++) {
            totalTime += times[i];
        }
        return totalTime;
    }
    void tic_f(int i) {
        times[i] = getTime();
    }
    void toc_f(int i) {
        times[i - 1] = getTime() - times[i - 1];
    }
    void tictoc(FILE* one) {
        std::cout << "line 0 - 1: " << std::fixed
        << std::setprecision(3) << times[0] << "ms" << std::endl;
        std::cout << "line 1 - 2: " << times[1] << "ms" << std::endl;
        std::cout << "line 2 - 3: " << times[2] << "ms" << std::endl;
        std::cout << "line 3 - 4: " << times[3] << "ms" << std::endl;
        std::cout << "line 4 - 5: " << times[4] << "ms" << std::endl;
    }
};
class timer_controller {
    timer timePiece[MAX_TIMER];
public
:
    timer_controller() {
    }
     void create(int i) {
         while (i != 0) {
             timePiece[i] = timer();
             i--;
         }
     }
     timer& operator[](int i) {
         return timePiece[i];
     }
    void display(FILE* one) {
        std::cout << "#Timer_1: " <<
        timePiece[0].getAllRdtsc() << "ms" << std::endl;
        std::cout << "#Timer_2: " <<
        timePiece[1].getAllRdtsc() << "ms" << std::endl;
    }
};
}  // namespace TIC_TOC

分析:

  • 这里其实是用一个循环来确定时间。每执行一次循环认为耗时一个_clock。这样就可以理解我们要如何确定时间差了。

答案:

#ifndef TIMER_H
#define TIMER_H

#include <stdio.h>
#include <memory.h>

#define MAX_LINE 10000
#define MAX_TIMER 5
#define _CLOCKS_PER_SEC 1000

static int _clock = 0;

inline void clock_f() { _clock += 50; }
inline double getTime() { return 1.0 * _clock / _CLOCKS_PER_SEC; }

namespace TIC_TOC {
class timer {
    double _timer[MAX_LINE];  // time for each line
    int _fromLine[MAX_LINE];  // line starting point
    int _lastLineNum;  // mark the ending line
    double _lastRdtsc;  // last time using getime()
    double _totalRdtsc;  // time for all lines
    public:
        timer() {
            memset(_timer, 0, sizeof(_timer));
            memset(_fromLine, 0, sizeof(_fromLine));
            _lastLineNum = -1;
            _lastRdtsc = _totalRdtsc = 0;
        }
        double getAllRdtsc() { return _totalRdtsc; }
        void tic_f(int line) {
            _lastLineNum = line;
            _lastRdtsc = getTime();
        }
        void toc_f(int line) {
            double t = getTime();
            _fromLine[line] = _lastLineNum;
            _timer[line] += t - _lastRdtsc;
            _totalRdtsc += _timer[line];
            _lastLineNum = line;
            _lastRdtsc = t;
        }
        void tictoc(FILE *out) {
        // 给出了一个文件指针。
            for (int i = 0; i < MAX_LINE; i++)
                if (_timer[i] != 0)
                    fprintf(out, "line %d - %d: %.3fms\n",
                        _fromLine[i], i, _timer[i]);
            fflush(out);
        }
};
class timer_controller {
    int count;  // count timers
    timer timePiece[MAX_TIMER];  // 5 timers at most for each timer_controller
    public:
        timer_controller() { count = 0; }
        void create(int input) { count = input; }
        timer& operator[](const int& input) { return timePiece[input]; }
        void display(FILE *out) {
            for (int i = 0; i < count; i++)
                fprintf(out, "#Timer_%d: %.3fms\n",
                    i+1, timePiece[i].getAllRdtsc());
            fflush(out);
        }
};
}  // namespace TIC_TOC

#endif

补充:


函数名: fflush
功 能: 清除读写缓冲区,需要立即把输出缓冲区的数据进行物理写入时
头文件:stdio.h
原型:int fflush(FILE *stream)
其中stream是要冲洗的流

int fprintf (FILE* stream, const char*format, [argument])
FILE*stream:文件指针
const char* format:输出格式
[argument]:附加参数列表
%d, %i 十进制有符号整数
%u 十进制无符号整数
%f 浮点数
%s 字符串
%c 单个字符
%p指针的值
%e, %E 指数形式的浮点数
%x无符号以小写十六进制表示的整数
%X 无符号以大写十六进制表示的整数
%o 无符号以八进制表示的整数
%g 自动选择合适的表示法[1]

程序清单 按以下步骤向视图类(CClockView)添加下列数据成员及成员函数。 (1) 添加表示年、月、日、时、分、秒的变量。 int year; int month; int day; int hour; int minute; int second; (2) 添加秒表的计数变量。 int watch; (3) 添加时钟的画笔及画刷变量。 CPen m_HouPen, m_MinPen, m_SecPen; // 各种针的画笔 CBrush m_MarkBrush; // 表盘标记的画刷 (4) 添加时钟控制变量。 CPoint m_Center; // 表的中心 double m_Radius; // 表的半径 CPoint m_Hour [2], m_OldHour [2]; // 时针当前及前一次位置 CPoint m_Minute [2], m_OldMin [2]; // 分针当前及前一次位置 CPoint m_Second [2], m_OldSec [2]; // 秒针当前及前一次位置 (5) 添加秒表的两个按钮位置变量。 CRect m_WatchStart; CRect m_WatchStop; (6) 添加两个函数,计算时钟各指针位置。 void SetClock (int hour, int minute, int second); CPoint GetPoint (int nLenth, int nValue); (7) 在视图类构造函数中增加初始化语句: CClockView::~CClockView() { //设定时间 year=2010; month=11; day=22; hour=0; minute=0; second=0; //设定画笔画刷 m_HouPen.CreatePen(PS_SOLID,5,RGB(255,0,0));//时针画笔 m_MinPen.CreatePen(PS_SOLID,3,RGB(0,0,250));//分针画笔 m_SecPen.CreatePen(PS_SOLID,1,RGB(0,0,0));//秒针画笔 m_MarkBrush.CreateSolidBrush(RGB(250,250,0)); //设定表芯位置 m_Center.x=222; m_Center.y=222; //设定时钟半径 m_Radius=222; //计算指针位置 SetClock(hour,minute,second); //设定秒表计数器及按钮位置 watch=0; m_WatchStart=CRect(480,310,560,340);//启动按钮 m_WatchStop=CRect(590,310,670,340);//停止按钮 } 编写指针位置函数SetClock和GETpOINT。 首先在ClockView.cpp文件头部下添加下面两行代码,以便进行数学计算。 #define PI 3.14159265258 #include"math.h" 然后添加下列代码: //计算个指针位置的函数 void CClockView::SetClock(int hour,int minute,int second) { hour=hour*5; hour=hour+minute/12; //保存时针原位置 m_OldHour[0]=m_Hour[0]; m_OldHour[1]=m_Hour[1];
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值