I am working on a timer that gives timestamps for every interrupt at any amount of milliseconds the user wants it to shoot off at.
struct itimerspec
takes seconds and nanoseconds when using:
it_interval
(a member of the struct)
I want to let the user specify the milliseconds, so I am doing a conversion in the constructor:
mNanoseconds = milliseconds * 1000000
(1,000,000 nanoseconds are in a single millisecond).
When the user enters anything under 1000 milliseconds, the timer will operate normally, but when I use 1000 milliseconds for the interval, the timer doesn't operate at all. It just sits there. I am unsure if my conversion is the issue, or what it could be.
mNanoseconds
is a uint64_t
, so I don't think the size of the mNanoseconds
integer is the issue.
Timer.cxx
std::mutex g_thread_mutex;
Timer::Timer(){};
Timer::Timer(int milliseconds)
: mMilliseconds(milliseconds)
{
mNanoseconds = milliseconds * 1000000;
std::cout << mNanoseconds << " Nanoseconds\n";
}
std::string Timer::getTime()
{
std::time_t result = std::time(nullptr);
return (std::asctime(std::localtime(&result)));
}
void Timer::startIntervalTimer()
{
struct itimerspec itime;
struct timeval tv;
int count = 0;
tv.tv_sec = 0; // seconds
tv.tv_usec = 0; // microseconds
gettimeofday(&tv, NULL);
//itime.it_interval.tv_sec = 2; //it_interval (value between successive timer expirations)
itime.it_interval.tv_nsec = mNanoseconds;
itime.it_value.tv_sec = itime.it_interval.tv_nsec;
int fd = timerfd_create(CLOCK_REALTIME, 0 );
timerfd_settime(fd, TFD_TIMER_ABSTIME, &itime, NULL);
while(count != 10)
{
uint64_t exp;
int n = read(fd, &exp, sizeof(exp));
//We don't lock the read(), but lock the actions we take when the read expires.
//There is a delay here- so not sure what that means for time accuracy
//Started to look into atomic locking, but not sure if that works here
g_thread_mutex.lock();
std::string t = getTime();
std::cout << t << " fd = " << fd << " count # " << count << std::endl;
g_thread_mutex.unlock();
count++;
}
stopTimer(fd, itime, tv);
}