Is there a way to reset the clock function?

Recommended Answers

All 7 Replies

I assume you mean clock() -- yes, just restart the program.

Well the title does says clock() function. Let me be more clear,
so no wise comment is made. I have a object spinning based on
the time the user presses the right key, If the user stops pressing
the right key then I need to reset the clock() function to 0. If there
is another way please suggest.

A start and an end would have the same difference as 0 and clock() if clock() were resettable, no?

call clock() at the start, then again at the end, and subtract the two.

clock_t t1, t2;
t1 = clock();
// do something here
t2 = clock();
clock_t diff = t2 - t1;

Will try it.

In general, no. But you can wrap the clock() inside a class and simulate a reset method:

class Clock
{
    private:
        clock_t naught;
    public:
        Clock():naught(0){} //constructor
        void reset()
        {
            naught=clock();
        }
        clock_t operator()()
        {
            return clock()-naught;
        }
};
//demonstration:
int main()
{
    using std::cout;using std::endl;
    Clock stopwatch;
    while(stopwatch()<2 * CLOCKS_PER_SEC);   //wait for 2 seconds
    cout<<"Our Clock()"<<stopwatch()<<"\t\t";//print our Clock()
    cout<<"Standard Clock()"<<clock()<<endl; //print the standard clock()
    
    
    stopwatch.reset();
    cout<<"\tOur Clock Reseted....\n";
    
    
    while(stopwatch()<2 * CLOCKS_PER_SEC);   //wait again
    cout<<"Our Clock()"<<stopwatch()<<"\t\t";//print our Clock()
    cout<<"Standard Clock()"<<clock()<<endl; //print the standard clock()
}

This is more or less like post#5 but in an encapsulated way.

Thanks, and btw I sent you a PM ancientDragon

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.