So I have been using a time profiler class (see bellow). It was working flawlessly untill some point (by not working I mean I suspected it was outputing weird values). I then created a new blank project from scratch and basically copy pasted the example from here: http://en.cppreference.com/w/cpp/chrono/duration/duration_cast. Instead, it now prints 1014 when its clearly supposed to be 1000, just like its been doibg untill yesterday! Once again, the same example from the link above used to work untill yesterday. I have no idea what happened. I restarted my machine but it did not work still.
Here's the time profiler class:
#pragma once #include <stdio.h> #include <time.h> #include <chrono> // C++11 #include <thread> #include <string> namespace profiler { // The time profiling class class Time { public: Time(const std::string& str) : m_str(str), m_start(std::chrono::system_clock::now()) { } virtual ~Time() { auto end = std::chrono::system_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - m_start).count(); printf("%s took %lli milliseconds\n", m_str.empty() ? "Block" : m_str.c_str(), duration); } private: std::string m_str; std::chrono::system_clock::time_point m_start; }; } #ifdef _DEBUG // Profile only if debugging. This profiles the time spent to process the block that this macro was called within #ifndef TIME #define TIME(str) profiler::Time timer__(str) #endif // TIME #else // If not debugging, do nothing #ifndef TIME #define TIME(str) do { } while(0) // This avoids empty statements #endif // TIME #endif // _DEBUG #ifndef SLEEP #define SLEEP(ms) std::this_thread::sleep_for(std::chrono::milliseconds(ms)); #endif // A working example of this profiler. Call EXAMPLE() and it should print 16 milliseconds #ifndef EXAMPLE #define EXAMPLE() \ profiler::Time timer__("Example that takes 16 milliseconds (value should match)"); \ std::this_thread::sleep_for(std::chrono::milliseconds(1)); \ std::this_thread::sleep_for(std::chrono::milliseconds(2)); \ std::this_thread::sleep_for(std::chrono::milliseconds(3)); \ std::this_thread::sleep_for(std::chrono::milliseconds(10)); #endif Here's the usage code:
#include <stdio.h> #include <chrono> #include <thread> int main() { auto start = std::chrono::system_clock::now(); std::this_thread::sleep_for(std::chrono::seconds(1)); auto end = std::chrono::system_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); printf("Block took %lli milliseconds\n", duration); return getchar(); } I'm using Visual Studio Ultimate 2012 on Windows 7 Professional 64 bits, if that helps.
sleep_forwill sleep for at least the specified sleep time. There's also the time consumed before and after the sleep method.