articles » current » assembly » x86 » return-cpu-speed-using-the-rdtsc-instruction

x86 Assembly: Return the CPU Speed Using RDTSC Instruction

Find the processor frequency in Hertz using the RDTSC assembly instruction

This code will return the base processor speed in simple Hertz (Hz). Divide it to convert to MHz and GHz. Notice that it requires the C Runtime Library for the function time().


TITLE 'extern "C" unsigned long long cpu_speed();'

.686P
.model FLAT

extern _time:PROC

PUBLIC	_cpu_speed

_TEXT	SEGMENT

_cpu_speed PROC NEAR

	push ebx
	push edi
	push esi


	push 0
	call _time   ; call the C Runtime function time() which is accurate to the second
	add esp, 4
	mov ebx, eax

	
loop1:
	push 0
	call _time
	add esp, 4
	cmp ebx, eax
	je loop1

	rdtsc        ; this will return the number of CPU ticks in EDX:EAX since the processor was reset
	
	mov edi, eax ; save EAX for later
	mov esi, edx ; save EDX for later


	push 0
	call _time
	add esp, 4
	mov ebx, eax

		
loop2:
	push 0
	call _time
	add esp, 4
	cmp ebx, eax
	je loop2

	rdtsc        ; again, returns the number of CPU ticks in EDX:EAX since the processor was reset
	
	sub eax, edi ; subtract the most recent CPU ticks from the original CPU ticks
	sbb edx, esi ; now, subtract with borrow

	pop esi
	pop edi
	pop ebx


	
exit:
	ret 0        ; the unsigned long long will return in EAX and EDX
_cpu_speed ENDP

_TEXT	ENDS
END

The driver code:


#include <iostream>
using namespace std;

extern "C" unsigned long long cpu_speed();

int main()
{
	unsigned long long Hz = cpu_speed();
	cout << Hz << "Hz" << endl;
	cout << (Hz / 1000000.0) << "MHz" << endl;
	cout << (Hz / 1000000000.0) << "GHz" << endl;
	cin.get();
	return 0;
}

The output from the above driver code:

3712015868Hz
3712.02MHz
3.71202GHz

This site uses cookies. Cookies are simple text files stored on the user's computer. They are used for adding features and security to this site. Read the privacy policy.
CLOSE