Python 2.x - QueryPerformanceCounter () on Windows

I would like to program my own watch object using Python. I would like it to be very, very accurate. I read that on Windows I could use QueryPerformanceCounter (). But how? I do not know a single C; Python 2.x only.

Can someone give me a hint on how to use this in Python to make an accurate clock on Win?

+4
source share
1 answer

I ported a C ++ example that you passed Python with a module ctypes:

C ++

LARGE_INTEGER StartingTime, EndingTime, ElapsedMicroseconds;
LARGE_INTEGER Frequency;

QueryPerformanceFrequency(&Frequency); 
QueryPerformanceCounter(&StartingTime);

// Activity to be timed

QueryPerformanceCounter(&EndingTime);
ElapsedMicroseconds.QuadPart = EndingTime.QuadPart - StartingTime.QuadPart;

ElapsedMicroseconds.QuadPart *= 1000000;
ElapsedMicroseconds.QuadPart /= Frequency.QuadPart;

Python

import ctypes
import ctypes.wintypes
import time

kernel32             = ctypes.WinDLL('kernel32', use_last_error=True)

starting_time        = ctypes.wintypes.LARGE_INTEGER()
ending_time          = ctypes.wintypes.LARGE_INTEGER()
elapsed_microseconds = ctypes.wintypes.LARGE_INTEGER()
frequency            = ctypes.wintypes.LARGE_INTEGER()

kernel32.QueryPerformanceFrequency(ctypes.byref(frequency)) 
kernel32.QueryPerformanceCounter(ctypes.byref(starting_time))

# Activity to be timed, e.g.
time.sleep(2)

kernel32.QueryPerformanceCounter(ctypes.byref(ending_time))

elapsed_microseconds = ending_time.value - starting_time.value
elapsed_microseconds *= 1000000
elapsed_microseconds /= frequency.value

print(elapsed_microseconds)

I really appreciate @eryksun's helpful tips !

- 2000000 (, 2000248.7442040185, ). round() int(), .

@eryksun, time.clock(), C, QueryPerformanceCounter().

, ctypes:

import time
starting_time = time.clock()

# Activity to be timed, e.g.
time.sleep(2)

ending_time = time.clock()

elapsed_microseconds = ending_time - starting_time
elapsed_microseconds *= 1000000

print(elapsed_microseconds)

, !

+4

Source: https://habr.com/ru/post/1648393/


All Articles