【问题标题】:Get CPU ticks and measured time获取 CPU 滴答声和测量时间
【发布时间】:2015-07-15 12:33:12
【问题描述】:

所以我想测量 C++ 中某些函数的时间,我尝试了很多方法。这是我的最终代码:

auto start = chrono::steady_clock::now();
clStart = clock();

for (int o=0; o<100;o++)
{
    sin(o);
   // Sleep(1);
}

auto end = chrono::steady_clock::now();
clEnd = clock();

auto difTime = end-start;
diff = chrono::duration <double,milli> (difTime).count(); //gives me 0
diffTicks = clEnd-clStart; //0 as well

当我在里面插入例如 Sleep() 函数时它工作正常,但是当使用 math.h 中的 sin 时,我总是得到 0 时间。这是为什么?我知道它可能已经优化,但是 0?我想将其与其他 sin 实现进行比较,但我不确定这里有什么问题。

【问题讨论】:

  • 试试int o=0; o&lt;100000;o++
  • @Thomas ...好吧,这很愚蠢 :D 谢谢,它似乎在起作用,顺便说一句,罪恶真的不需要打勾吗?我以为时钟不会返回滴答数?

标签: c++ time cpu clock chrono


【解决方案1】:

计算100个sin的时间很短,应该用

auto start = chrono::steady_clock::now();
clStart = clock();

for (int o=0; o<100000;o++)
{
    sin(o);
   // Sleep(1);
}

auto end = chrono::steady_clock::now();
clEnd = clock();

auto difTime = end-start;
diff = chrono::duration <double,milli> (difTime).count();
diffTicks = clEnd-clStart;

改为。

此外,您的代码以毫秒为单位。我建议你使用chrono::duration &lt;double, nano&gt; (diff).count(),它使用纳秒来获得更高的精度。


来自文档:

持续时间中存储的唯一数据是 Rep 类型的滴答计数。如果 Rep 是浮点数,则持续时间可以表示滴答的分数。 Period 包含在持续时间类型的一部分中,并且仅在不同持续时间之间转换时使用。

这意味着这不是您正在测量的 CPU 滴答声

【讨论】:

    【解决方案2】:

    我认为最好使用内部滴答计数。我通常使用两个类来帮助我:

     class PACKAGE Profiler
     {
        public:
        Profiler()
        {
            totalTime=0;
            PCFreq = 0.0;
            numberOf =0.0;
            QueryPerformanceFrequency(&li);
            PCFreq = double(li.QuadPart)/1000.0;
    
            QueryPerformanceCounter(&li);
            CounterStart = li.QuadPart;
    
        }
        __int64 CounterStart;
        LARGE_INTEGER li;
        double totalTime;
        double PCFreq;
        long numberOf;
    
     };
    
     class PACKAGE Profiterol
     {
        private:
            Profiler* m_myprofiler;
        public:
        Profiterol(Profiler* a_prof)
        {
            m_myprofiler = a_prof;
            QueryPerformanceCounter(&m_myprofiler->li);
            m_myprofiler->CounterStart = m_myprofiler->li.QuadPart;
            m_myprofiler->numberOf++;
        }
        ~Profiterol()
        {
            QueryPerformanceCounter(&m_myprofiler->li);
            m_myprofiler->totalTime += double(m_myprofiler->li.QuadPart-m_myprofiler->CounterStart)/m_myprofiler->PCFreq;
        }
    
     };
    

    然后,在你的代码中你必须这样做:

    Profiler partial2;
    
    {
      Profiterol tmp(&partial2);
            for (int o=0; o<100;o++)
            {
                sin(o);
               // Sleep(1);
            }
    }
    String strMeasureTime = String(partial2.totalTime) + "(" + String(partial2.numberOf)
    

    在strMeasureTime你会有时间。

    【讨论】:

    • 谢谢,我也试试这个
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-07
    • 2018-07-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多