Re: getting nanoseconds of system time with C++

From: Marcin Kalicinski (
Date: 03/09/04

Date: Tue, 9 Mar 2004 16:55:42 +0100

Użytkownik "rsr" <> napisał w wiadomości

"John Harrison" <> wrote in message
> "uli" <> wrote in message
> news:c2k5v7$bgm$
> > Hi all,
>> ...
> > So it seems, that the MVC++ does not.
> > Because I'm not so familiary with C++, I wanted to ask if someone could
> > give
> > me some hints, how to realize the possibility to get the NANOSECONDS of
> > the SystemTime in C++ to make it run on any system.
> > Thanx a lot in advance!
> > best regards,
> > uli

>You can use:

>GetTickCount - The GetTickCount function retrieves the number of
>milliseconds that have elapsed since the system was started
>time (CRT function) - The time function returns the number of seconds
>elapsed since midnight (00:00:00), January 1, 1970.
>asm rdtsc - read time stamps counter - not sure about this one, this timer
>probably works with cpu clock
>GetSystemTime - The GetSystemTime function retrieves the current system
>and time.There are miliseconds, seconds, minutes etc in result
>QueryPerformanceCounter - function retrieves the current value of the
>high-resolution performance counter.
>QueryPerformanceFrequency - function retrieves the frequency of the
>high-resolution performance counter, if one exists.

Here's the actual code to retrieve number of 80x86 CPU clock ticks passed
since the CPU was last started. It will work on Pentium and above (386/486
not supported). This code is actually MS Visual C++ specific, but can be
probably very easy ported to whatever else, as long as it supports inline

    inline __int64 GetCpuClocks()

        // Counter
        struct { int32 low, high; } counter;

        // Use RDTSC instruction to get clocks count
        __asm push EAX
        __asm push EDX
        __asm __emit 0fh __asm __emit 031h // RDTSC
        __asm mov counter.low, EAX
        __asm mov counter.high, EDX
        __asm pop EDX
        __asm pop EAX

        // Return result
        return *(__int64 *)(&counter);


This function has also the advantage of being extremely fast - it usually
takes no more than 50 cpu cycles to execute.

Best regards,