Assembly CPU frequency measuring algorithm

后端 未结 10 2024
时光取名叫无心
时光取名叫无心 2020-12-01 14:29

What are the common algorithms being used to measure the processor frequency?

10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-01 15:08

    I use the following (pseudo)algorithm:

    basetime=time();    /* time returns seconds */
    
    while (time()==basetime);
    stclk=rdtsc();    /* rdtsc is an assembly instruction */
    
    basetime=time();
    while (time()==basetime
    endclk=rdtsc();
    
    nclks=encdclk-stclk;
    

    At this point you might assume that you've determined the clock frequency but even though it appears correct it can be improved.

    All PCs contain a PIT (Programmable Interval Timer) device which contains counters which are (used to be) used for serial ports and the system clock. It was fed with a frequency of 1193182 Hz. The system clock counter was set to the highest countdown value (65536) resulting in a system clock tick frequency of 1193182/65536 => 18.2065 Hz or once every 54.925 milliseconds.

    The number of ticks necessary for the clock to increment to the next second will therefore depend. Usually 18 ticks are required and sometimes 19. This can be handled by performing the algorithm (above) twice and storing the results. The two results will either be equivalent to two 18 tick sequences or one 18 and one 19. Two 19s in a row won't occur. So by taking the smaller of the two results you will have an 18 tick second. Adjust this result by multiplying with 18.2065 and dividing by 18.0 or, using integer arithmetic, multiply by 182065, add 90000 and divide by 180000. 90000 is one half of 180000 and is there for rounding. If you choose the calculation with integer route make sure you are using 64-bit multiplication and division.

    You will now have a CPU clock speed x in Hz which can be converted to kHz ((x+500)/1000) or MHz ((x+5000000)/1000000). The 500 and 500000 are one half of 1000 and 1000000 respectively and are there for rounding. To calculate MHz do not go via the kHz value because rounding issues may arise. Use the Hz value and the second algorithm.

提交回复
热议问题