I have an assignment where i'm supposed to measure some delays between packets without using any CPU or OS clock functions(it may sound dumb, but it makes sense within the virtual network i have to make) and have decided to write my own clock class, similar with how we measure time with microcontrollers using the internal oscillator whose frequency we know.
I began writing a small Clock
class that i would make a private member of the TCP
class to simply play the role of an internal clock that ticks size_t period
times per millisecond. Nothing fancy and accuracy of time measurement is of no importance.
#include <iostream>
#include <cstdio>
#include <thread>
class Clock{
public:
Clock();
~Clock();
Clock(const size_t& period);
size_t getElapsedTime();
void run();
private:
size_t period;
size_t elapsedTime;
bool running;
protected:
};
Clock::Clock() :period(1000000), elapsedTime(0), running(true)
{
std::thread t(run);
t.detach();
}
Clock::Clock(const size_t& period) : elapsedTime(0), running(true) {
this->period = period;
}
void Clock::run() {
while (this->running){
for ( int i = 0; i < period; ++i){;}
++elapsedTime;
}
}
Clock::~Clock(){
}
std::size_t Clock::getElapsedTime() {
return elapsedTime;
}
int main(){
Clock clk(1000000);
return 0;
}
The problem i have is that i cannot seem to get this thread to work. I want to have it running non-stop until i destruct the Clock
object and when a certain event within the large program happens, i want to call getElapsedTime()
and see how long it took for that to trigger.
When writing std::thread t(run);
i get an error saying error: invalid use of non-static member function 'void Clock::run()'
but making the method static
yields even more errors.