【发布时间】:2015-10-20 17:29:05
【问题描述】:
所以我一直在使用时间分析器类(见下文)。 它一直完美地工作到某个时候(不工作我的意思是我怀疑它正在输出奇怪的值)。然后我从头开始创建了一个新的空白项目,基本上从这里复制粘贴示例:http://en.cppreference.com/w/cpp/chrono/duration/duration_cast。相反,当它显然应该是 1000 时,它现在打印 1014,就像它一直到昨天一样!再一次,上面链接中的相同示例曾经工作到昨天。我不知道发生了什么。我重新启动了我的机器,但它仍然无法工作。
这是时间分析器类:
#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();
}
如果有帮助,我在 Windows 7 Professional 64 位上使用 Visual Studio Ultimate 2012。
【问题讨论】:
-
它按预期运行。这里有两件事要考虑。首先,
sleep_for将休眠 at least 指定的休眠时间。还有 sleep 方法前后消耗的时间。 -
@wendelbsilva 我知道这个睡眠功能可能不是非常准确,而且 SO 可能会干扰一点,但我坚信有些地方出了问题。我一直在用它来测量解析某些文件所花费的时间。平均过去是 10 到 15 毫秒,但现在有时会打印零!现在这个解析不可能花费 0 毫秒。太奇怪了,它甚至会像以前一样打印 15 毫秒,有时甚至是 0。
-
您计算机上的另一个应用程序是否调用 timeBeginPeriod temporarilt 提高了您的时间分辨率?游戏对此特别有罪(注意更改计时器周期通常是一个非常糟糕的主意)
-
@Mike 我不明白