關於擷取CPU的脈衝問題

來源:互聯網
上載者:User

看到有兄弟問我如何使用CPU脈衝數來測量執行速度,這個其實很簡單,讀TSC寄存器(每個時鐘脈衝TSC寄存器加一)而已,就是以下代碼就可以了。由於彙編是VC風格的,所以這段代碼僅僅用於Windows環境,使用方法看函數名就應該知道了,這應該是目前最精確的計時器了,可以用來衡量最核心代碼的執行效率。

 

#ifndef    __CPU_H__
#define    __CPU_H__

#pragma warning ( push )
#pragma warning ( disable : 4035 )

class CCPU
{
private:
#ifdef WIN32
    static unsigned int    readTimeStampCounterLow()
    {
        _asm
        {
            _emit    0Fh        ;RDTSC
            _emit    31h
        }
        //                        returns eax
    }

    static unsigned    int    readTimeStampCounterHigh()
    {
        _asm
        {
            _emit    0Fh        ;RDTSC
            _emit    31h
            mov    eax, edx ;eax=edx
        }
        //                        returns eax
    }

    static unsigned    __int64    readTimeStampCounter()
    {
        _asm
        {
            _emit    0Fh        ;RDTSC
            _emit    31h
        }
        //                        returns edx:eax
    }

    static void readTimeStampCounter(unsigned int *uHigh, unsigned int *uLow)
    {
        _asm
        {
            _emit    0Fh        ;RDTSC
            _emit    31h

            mov    ebx, uHigh
            mov    dword ptr [ebx], edx
            mov    ebx, uLow
            mov    dword ptr [ebx], eax
        }
    }
#endif
public:
    unsigned int tH;
    unsigned int tL;

    void start_clock()
    {
    #ifdef WIN32
        readTimeStampCounter(&tH,&tL);
    #endif
    }

    int get_timespan()
    {
    #ifdef WIN32
        unsigned int H;
        unsigned int L;
        readTimeStampCounter(&H,&L);
        if(H==tH) return (L-tL);
        else return(tL-L);
    #else
        return 0;
    #endif
    }
   
};

static CCPU CpuClock;

#pragma warning ( pop )

#endif    //__CPU_H__

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.