Getting Date & Time ( Getting wrong result )

Hi,I'm new to C++ and trying to get time before & after executing for loop. After executing for loop it points same datetime. My code is below,

class DateTime
{
public:
static char* GetDate()
{
time_t rawtime;
time (&rawtime);
return ctime(&rawtime);
}
};

int main()
{
const char* beforeTime=DateTime::GetDate();
for (int I=0;I<100000;I++)
{
cout<<I<<"\t";
}

const char* afterTime=DateTime::GetDate();
cout << "Execution Time : " << beforeTime << "\t" << afterTime << endl;
return 0;
}

My Output :

Execution Time : Wed May 22 15:38:55 2013
Wed May 22 15:38:55 2013

It should not be same bz it takes more than 1 min.

Could anyone please guide me how to fix this ?
Last edited on
Buffer which holds result of ctime() is shared across all calls to it, so each succesive call to ctime() will overwrite previous data.
Possible solutions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const char* beforeTime=DateTime::GetDate();
cout << "Execution Time : " << beforeTime << "\t";
//Wait here
const char* afterTime=DateTime::GetDate();
cout << afterTime << endl;

//or

char beforeTime[100];
strncpy(beforeTime, DateTime::GetDate(), 99);
//wait here
char afterTime[100];
strncpy(afterTime, DateTime::GetDate(), 99);
//output here 

BTW, do not simulate wait using loops. Use Sleep() function or, better,
http://en.cppreference.com/w/cpp/thread/sleep_for

Also you may find this interesting:
http://en.cppreference.com/w/cpp/chrono
http://www.cplusplus.com/reference/chrono/
Hi MiiNiPaa,

Thanks for your valuable answer. Its working perfectly. Thanks.
Last edited on
Topic archived. No new replies allowed.