IA32周期計數器

來源:互聯網
上載者:User

IA32處理器包含一個運行在時針周期級的計時器,這個計時器是一個特殊的寄存器,每個刻度它都會加1。IA32並提供特殊的指令讀取該計時器,利用該計時器,可以很容易的計算出CPU的刻度(頻率)。

 程式如下:

#include <windows.h>
//#include <stdlib.h>
#include <stdio.h>

static unsigned cyc_hi = 0;
static unsigned cyc_lo = 0;
/*寄存器使用慣例:
**eax,ecx,edx由調用者儲存,ebx,esi,edi由被調用者儲存
*/
//vc下的嵌入彙編
void access_counter(unsigned *hi, unsigned *lo)
{
    _asm{
        rdtsc
        mov ecx,hi
        mov dword ptr[ecx],edx
        mov ecx,lo
        mov dword ptr[ecx],eax
    }
}
//gcc的嵌入彙編
// void access_counter(unsigned *hi, unsigned *lo)
// {
//     asm("rdtsc; movl %%edx,%0; movl %%eax,%1"   /* Read cycle counter */
//         : "=r" (*hi), "=r" (*lo)                /* and move results to */
//         : /* No input */                        /* the two outputs */
//     : "%edx", "%eax");
// }

/* Record the current value of the cycle counter. */
void start_counter()
{
    access_counter(&cyc_hi, &cyc_lo);
}

/* Return the number of cycles since the last call to start_counter. */
double get_counter()
{
    unsigned ncyc_hi, ncyc_lo;
    unsigned hi, lo, borrow;
    double result;
    
    /* Get cycle counter */
    access_counter(&ncyc_hi, &ncyc_lo);
    
    /* Do double precision subtraction */
    lo = ncyc_lo - cyc_lo;
    borrow = cyc_lo > ncyc_lo;
    hi = ncyc_hi - cyc_hi - borrow;
    result = (double) hi * (1 << 30) * 4 + lo;
    return result;
}

/* $begin mhz */
/* Estimate the clock rate by measuring the cycles that elapse */ 
/* while sleeping for sleeptime seconds */
double mhz(int verbose, int sleeptime)
{
    double rate;
    
    start_counter();
    //c庫的sleep函數以秒為單位
    //sleep(sleeptime);
    //win32 API的Sleep以毫秒為單位
    Sleep(sleeptime);
    //linux
    //rate = get_counter() / (1e6*sleeptime);

    //windows
    rate = get_counter() / (1e3*sleeptime);

    if (verbose) 
        printf("Processor clock rate ~= %.1f MHz\n", rate);
    return rate;
}
int main()
{
    int i;
    for (i=0;i<10;i++)
    {
        //線程睡眠1秒
        //mhz(1,1);  //linux下
        //windows下
        mhz(1,1000); 
    }
    return 0;
}

 windows下輸出:

 

Linux下輸出:

 

原生處理器為:Pentium(R) 4 CPU 1.60GHz

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.