Поэтому я использовал класс профилировщика времени (см. Ниже). До какого-то момента он работал безупречно (под неработающим я подразумеваю, что я подозревал, что он выводит странные значения). Затем я создал новый пустой проект с нуля и скопировал пример отсюда: http://en.cppreference.com/w/cpp/chrono/duration/duration_cast. Вместо этого теперь он печатает 1014, когда явно должно быть 1000, точно так же, как это делалось до вчерашнего дня! Еще раз, тот же пример из приведенной выше ссылки работал до вчерашнего дня. Я понятия не имею, что произошло. Я перезапустил свою машину, но она все еще не работала.
Вот класс профилировщика времени:
#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
Вот код использования:
#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();
}
Я использую Visual Studio Ultimate 2012 в 64-разрядной версии Windows 7 Professional, если это поможет.
sleep_for
будет спать в течение по крайней мере указанного времени ожидания. Есть также время, затраченное до и после метода сна. - person wendelbsilva   schedule 20.10.2015