
Originally Posted by
DillByrne
here's a predefined function to return the system time. mabye it can be of help, its in the stdlib.h header,
Code:
#include<iostream>
#include<string>
#include<stdlib.h>
using namespace std;
main()
{
// Get the current time in seconds since midnight 1/1/70.
time_t now;
time(&now);
printf("Its %.24s\n",ctime(&now));
}
Thanks, I am familiar with ctime(). The issue I had is converting a struct timespec to something that I can use to formulate the time.
After resting my thoughts on this issue for a few hours, I have realized that I can convert the tv_sec field of the timespec to a time_t, and then yield the date (using ctime). Then all I have to do is append the nanoseconds. However that is easier stated than done.
What are my options with this, other than writing a boat-load of code? Here's a sample app that unfortunately does nothing with the tv_nsec field:
Code:
#include <ctime>
#include <iostream>
int main()
{
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
time_t tt = ts.tv_sec;
std::cout << ctime(&tt) << std::endl;
// I would really like to use tv_nsec, so that my final output looked
// something like:
//
// Thu Apr 2 22:01:32.nnnnnnnnn 2009
//
// where nnnnnnnnn is the nanoseconds.
}
Btw, to compile the code above:
----------------------------------------------
EDIT
I suppose this could suffice... I just wish there was a cleaner way:
Code:
#include <ctime>
#include <cstdio>
#include <iostream>
#include <iomanip>
int main()
{
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
char day[4], mon[4];
int wday, hh, mm, ss, year;
sscanf(ctime((time_t*) &(ts.tv_sec)), "%s %s %d %d:%d:%d %d",
day, mon, &wday, &hh, &mm, &ss, &year);
std::cout << day << ' '
<< mon << ' '
<< std::setw(2) << std::setfill(' ') << wday << ' '
<< std::setfill('0')
<< hh << ':' << mm << ':' << ss << '.' << ts.tv_nsec << ' '
<< year
<< std::endl;
}
Bookmarks