In: Computer Science
C++ How do I initialize a clock to 0 and run it constantly throughout the program? THEN, how do I get the time at that moment multiple times? As in id like to set the
clock = 0,
do stuff
do stuff
get time now, store it
do stuff
get time now, store it
then also be able to do arithmetic on it, for instance, last time - current time = 2 seconds. I made it sound complicated but I believe this is very easy.
Code -
#include <iostream>
#include <cstdio>
#include <ctime>
#include <cstdlib>
using namespace std;
int main() {
std::clock_t startTime;
double endTime;
//initialize start time
startTime = std::clock();
//print the start time
cout<<"Start Time "<<startTime<<endl;
/* Your algorithm here */
/*do stuff
do stuff*/
//calculate time after some interval
std::clock_t time1 = std::clock();
//print the time
cout<<"Time in between "<<time1<<endl;
//calculate the time difference from now to the start time and
print the result
double secondDifference = ( time1 - startTime ) / (double)
CLOCKS_PER_SEC;
cout<<"Time difference "<<secondDifference<<"
second"<<endl;
/*do stuff*/
//calculate time after some interval
std::clock_t time2 = std::clock();
//print the time
cout<<"Time at end "<<time2<<endl;
//calculate the time difference from now to the start time and
print the result
secondDifference = ( time2 - startTime ) / (double)
CLOCKS_PER_SEC;
cout<<"Time difference "<<secondDifference<<"
second"<<endl;
}
Screenshots -