[Python-Dev] time.clock() on windows

Sturla Molden sturla at molden.no
Fri Oct 23 19:18:46 CEST 2009


Kristján Valur Jónsson skrev:
> Thanks, I'll take a look in that direction.
>
>   
I have a suggestion, forgive me if I am totally ignorant. :-)

Sturla Molden



#include <windows.h>

union __reftime {
    double   us;
    __int64  bits;
};

static volatile union __reftime __ref_perftime, __ref_filetime;


double clock()
{
    __int64 cnt, hz, init;
    double us;
    union __reftime ref_filetime;
    union __reftime ref_perftime; 
    for (;;) {
        ref_filetime.bits = __ref_filetime.bits;
        ref_perftime.bits = __ref_perftime.bits;
        if(!QueryPerformanceCounter((LARGE_INTEGER*)&cnt)) goto error;
        if(!QueryPerformanceFrequency((LARGE_INTEGER*)&hz)) goto error;
        us = ref_filetime.us + ((double)(1000000*cnt)/(double)hz - 
ref_perftime.us);
        /* verify that values did not change */
        init = InterlockedCompareExchange64((LONGLONG*)&__ref_filetime.bits,
                                            (LONGLONG)ref_filetime.bits,
                                            (LONGLONG)ref_filetime.bits);
        if (init != ref_filetime.bits) continue;
        init = InterlockedCompareExchange64((LONGLONG*)&__ref_perftime.bits,
                                            (LONGLONG)ref_perftime.bits,
                                            (LONGLONG)ref_perftime.bits);
        if (init == ref_perftime.bits) break;
    }
    return us;
error:
    /* only if there is no performance counter */
    return -1; /* or whatever */
}


int periodic_reftime_check()
{
    /* call this function at regular intervals, e.g. once every second 
*/   
    __int64 cnt1, cnt2, hz;
    FILETIME systime;
    double ft;
    if(!QueryPerformanceFrequency((LARGE_INTEGER*)&hz)) goto error;
    if(!QueryPerformanceCounter((LARGE_INTEGER*)&cnt1)) goto error;
    GetSystemTimeAsFileTime(&systime);
    __ref_filetime.us = (double)(((((__int64)(systime.dwHighDateTime)) 
<< 32)
            | ((__int64)(systime.dwLowDateTime)))/10); 
    if(!QueryPerformanceCounter((LARGE_INTEGER*)&cnt2)) goto error;
    __ref_perftime.us = 500000*(cnt1 + cnt2)/((double)hz);
    return 0;
error:
    /* only if there is no performance counter */
    return -1;   
}











More information about the Python-Dev mailing list