开发者

timer outside of a class

I have the following code and I wanted to create a class that encapsulates the timer but the trouble I'm having is using the timer after declaring the class. I posted another block of code to show an example of how I want to use the timer.

double diffclock(clock_t clock1,clock_t clock2)
{
    double diffticks=clock1-clock2;
    double diffms=(diffticks*1000)/CLOCKS_PER_SEC;
    return diffms;
}
void some_function()
{   
    clock_t begin = clock();

    //do something
    clock_t end=clock();
    cout << "Time elapsed: " << double(diffclock(end,begin)) << " ms"<< endl;

}

this is the header file

#ifndef SPECIALCLOCK_H
#define SPECIALCLOCK_H
#include <ctime>

class specialclock
{
    private:

    public:

    specialclock(){}
    ~specialclock(){}
    double diffclock(clock_t clock1,clock_t clock2);
};
double specialc开发者_运维知识库lock::diffclock(clock_t clock1,clock_t clock2)
{
    double diffticks=clock1-clock2;
    double diffms=(diffticks*1000)/CLOCKS_PER_SEC;
    return diffms;
}
#endif

And this the the main file

#include "specialclock.h"

int main()
{

   specialclock timer;

//how would I use the timer here?

   return 0;
}


In your specialclock class's constructor, store the current value of the clock to a member variable.

In your specialclock class's destructor, query the current value of the clock again, subtract your member variable's value from the current value, and print out the result.

Then you can declare a specialclock item at the top of any function/method, and it will automatically print out how long the function/method took to run.


The way you have your class set up doesn't really make sense. I have a simple timer class that works like this:

Timer MyTimer;

// Do stuff...

std::cout << "Execution took " << MyTimer.Seconds() << " seconds." << std::endl;

Is this what you're looking for? If so, my class is set up like the following:

class Timer
{
    std::clock_t ReferencePoint;

    public:

    Timer()
    {
        // Set the reference point to the current time.
    }

    double Seconds()
    {
        // Return the difference between the current time and the
        // reference point.
    }
};

This is simplified for the sake of clarity. You can see my full source here and here.


#include <iostream>
#include "specialclock.h"

int main()
{

       specialclock timer;
       clock_t begin = clock();
       //do something here
    clock_t end = clock();
        std::cout << "Time elapsed: " << double(timer.diffclock(end,begin)) << " ms"<< std::endl;

   return 0;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜