4

I have a python script that calls a USB-based data-acquisition C# dotnet executable. The main python script does many other things, e.g. it controls a stepper motor. We would like to check the relative timing of various operations, for that purpose the dotnet exe generates a log with timestamps from C# Stopwatch.GetTimestamp(), which as far as I know yields the same number as calls to win32 API QueryPerformanceCounter().

Now I would like to get similar numbers from the python script. time.clock() returns such values, unfortunately it subtracts the value obtained at the time of 1st call to time.clock(). How can I get around this? Is it easy to call QueryPerformanceCounter() from some existing python module or do I have to write my own python extension in C?

I forgot to mention, the python WMI module by Tim Golden does this: wmi.WMI().Win32_PerfRawData_PerfOS_System()[0].Timestamp_PerfTime , but it is too slow, some 48ms overhead. I need something with <=1ms overhead. time.clock() seems to be fast enough, as is c# Stopwatch.GetTimestamp().

TIA, Radim

Radim Cernej
  • 875
  • 1
  • 10
  • 21

2 Answers2

8

Have you tried using ctypes?

from ctypes import *
val = c_int64()
windll.Kernel32.QueryPerformanceCounter(byref(val))
print val.value
luc
  • 41,928
  • 25
  • 127
  • 172
  • 1
    Works well, I am able to get readouts about 0.5ms apart (vs. 48ms with WMI). Thank you, Luc. – Radim Cernej Dec 13 '10 at 16:07
  • Here's an extension of the above, with micros(), millis(), delay(), and delayMicroseconds() functions for Python in Windows: http://stackoverflow.com/questions/38319606/how-to-get-millisecond-and-microsecond-resolution-timestamps-in-python. Thanks @luc for providing the syntax of accessing QueryPerformanceCounter in Python! – Gabriel Staples Jul 12 '16 at 03:42
  • @luc, should you be using `val = c_uint64()` instead of `val = c_int64()`? – Gabriel Staples Sep 07 '16 at 12:53
  • or maybe not??? Since this (https://msdn.microsoft.com/en-us/library/windows/desktop/aa383713(v=vs.85).aspx) shows the "QuadPart" being a signed 64-bit integer. – Gabriel Staples Sep 07 '16 at 12:56
0

You could just call the C# StopWatch class directly from Python couldn't you? Maybe a small wrapper is needed (don't know Python/C# interop details - sorry) - if you are already using C# for data acquisition, doing the same for timings via Stopwatch should be simpler than anything else you can do.

Steve Townsend
  • 53,498
  • 9
  • 91
  • 140