I am writing a macro to time function, example below in simplified form:
namespace Tool {
static std::mutex timer_mutex{};
static std::map<std::thread::id, unsigned long> timers{};
struct Timer {
Timer(const std::string &name);
~Timer();
std::string funcName;
std::chrono::high_resolution_clock::time_point time;
};
}
Tool::Timer::Timer(const std::string &name): funcName(name),
time(std::chrono::high_resolution_clock::now()){}
{
std::lock_guard<std::mutex> lock(timer_mutex);
if (timers[std::this_thread::get_id()] < std::numeric_limits<unsigned long>::max())
timers[std::this_thread::get_id()]++;
}
Tool::Timer::~Timer()
{
std::lock_guard<std::mutex> lock(timer_mutex);
if (timers[std::this_thread::get_id()] > 0)
std::cout << getTheTimeNow() - time <<"n";
}
#define TIME_FUNC Tool::Timer(static_cast<const char *>(__PRETTY_FUNCTION__))
void doSomemoreWork()
{
TIME_FUNC;
//some work
}
int main()
{
TIME_FUNC;
doSomemoreWork();
//doing some work...
}
The main idea is, TIME_FUNC will construct a Timer struct and record the current time and thread, when a function ended, Timer will be destruct and i will cout the time difference between the time when construction and destruction.
The problem is, sometimes i don’t get the std::cout from destructor. Is it data race or should i just not use macro ? any help greatly appreciated.