How to get ticks from QueryPerformanceCounter in C#?

queryperformancecounter nanoseconds
queryperformancecounter stopwatch
kernel32 queryperformancecounter
windows high resolution timer
c# high resolution timer
qpc ticks
c# stopwatch

I need to replace Stopwatch to avoid using getters for its properties. I am going to implement it using QueryPerformanceCounter. I only need ticks nothing else.

Can anyone provide a code snipet please, to get correct ticks (1/10000 of ms) or any other small but stable value.

Please note my server sets clock granularity down to 0.5 ms (not sure if it affects QueryPerformanceCounter) but just for you to know.

Please also note - I do not need a timer. I only need to measure time intervals between parts of code.

EDIT: to avoid confusion I really want to know what is lpPerformanceCount in QueryPerformanceCounter(out long lpPerformanceCount);

private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);

private static extern bool QueryPerformanceFrequency(out long lpFrequency);

Taken from

Old but it should still work

EDIT: The internals of StopWatch actually use QueryPerformanceCounter, so using the managed code should provide identical results, with better compatibility.

.net 4.0, .net 4.0 - How to get ticks from QueryPerformanceCounter in C#? - I'm going to implement it using QueryPerformanceCounter I just need to tick and nothing� In C# .Net, I can the do the following: long ticks = DateTime.Now.Ticks; How can I achieve the same result using C++? (I'm not so familiar with C++ libraries). Thanks. What you are looking for is clock() which returns the number of ticks since the program started. To translate "Ticks" into something meaningful, divide by the macro CLOCKS_PER_SEC.


You don't have to instantiate a Stopwatch object, GetTimestamp should return the number of ticks regardless of its context.

Acquiring high-resolution time stamps, The primary API for native code is QueryPerformanceCounter (QPC). This example shows how to use QPC in C and C++ native code. QuadPart; // // We now have the elapsed number of ticks, along with the // number of� Important. Because the value of the TickCount property value is a 32-bit signed integer, if the system runs continuously, TickCount will increment from zero to Int32.MaxValue for approximately 24.9 days, then jump to Int32.MinValue, which is a negative number, then increment back to zero during the next 24.9 days.

Do NOT use StopWatch for high resolution timing without testing it. It has been a few years since I have tested it, but at that time it gave the default windows time resolution. You can tell because really, really fast things will take either 0 time or 10-15 milliseconds if it is using the default windows resolution (the default resolution is actually the resolution of thread context switches, presumably the default windows clock is updated at each context switch, which is about every 10-15 milliseconds).

How to use QueryPerformanceCounter?, How to get ticks from QueryPerformanceCounter in C#?, High resolution timing is supported in Win32 by the QueryPerformanceCounter() and� Using QueryPerformanceCounter(QPC) or the CPU’s ticks (rdtsc) can provide the resolution between the system time ticks. Such an approach was used in the MSDN magazine article Kevin cited. Though these approaches may have drift (e.g., due to frequency scaling), etc and therefore need to be synced to the system time.

I use the following class that gives the time accurate to 100ns on my system.

public class MStopwatch : Stopwatch
    private double _frequencyScaler;

    public MStopwatch()
        _frequencyScaler = 1.0 / Stopwatch.Frequency;

    public double ElapsedSeconds
            return ElapsedTicks * _frequencyScaler;


How to get timestamp of tick precision in .NET / C#?, How to get timestamp of tick precision in .NET / C#?. c# timestamp .net ticks to Apparently, StopWatch / QueryPerformanceCounter is the way to go, but it can� .NET DateTime Ticks Converter Online. Three way Converter: .NET Core / .NET Framework Ticks (C# DateTime.Ticks) ⇄ Date Time ⇄ Unix Timestamp.

NOT A DIRECT ANSWER (but Potentially necessary support info follows):

Some of the provided answers are pretty good to directly answer your question. However, to accomplish what you're trying to do, I would like to add a couple notes.

First, take into account the timing overhead of the just-in-time (jit) compiler which happens at runtime. Any code where you grab the initial timestamp then do stuff, and then grab a final timestamp to subtract t2-t1 for the delta, for any functionality inside of stuff, if you include any functions you haven't called yet during the current process then the first time you call it, you will pay for the jit overhead to compile the bytecode into native code. In this case, the cost is not representative of the actual runtime cost of performance critical code which is presumably code that is called frequently and yet whose jit cost is paid just once (on the first call to it in the process). So call the timed code multiple times, throw out the first timing, and take an average.

Furthermore beware of the runtime costs of the garbage collector. If you are just playing around, then it might be possible and interesting to benchmark code that strictly avoids allocating new objects. But sometimes this is not easy particularly when you are calling functions whose implementations you cannot change. Also, I must grant you that the real world performance overhead of production code cannot avoid garbage collection overhead so getting a realistic figure should include this overhead. That said, if your stuff includes code that allocates new objects, then it may kick off the garbage collector which will be expensive so prepare yourself for some potential outliers that you might want to throw out.

Second, the good answers provided the code to declare external functions to call from system dlls and that's great. Getting these signatures correct in the general case can be a nuisance sometimes so I would like to mention a great resource for this: A search for QueryPerformanceCounter gave me the signatures that put me a cut-and-paste away from the answer already given and it is a great resource for any system calls you want to make.[All]

High Resolution Timer, C standard library provides clock() function, which can be used to measure the QueryPerformanceCounter() is used to get the current elapsed ticks, and� I am going to implement it using QueryPerformanceCounter. I only need ticks nothing else. Can anyone provide a code snipet please, to get correct ticks (1/10000 of ms) or any other small but stable value. Please note my server sets clock granularity down to 0.5 ms (not sure if it affects QueryPerformanceCounter) but just for you to know.

c# — �C�mo obtener la marca de tiempo de la precisi�n de tick en , �C�mo obtener la marca de tiempo de la precisi�n de tick en .NET/C #? Aparentemente, StopWatch / QueryPerformanceCounter es el camino a seguir, pero FromSeconds(10); public static DateTime UtcNow { get { if ((_stopWatch == null)� I avoid ticks whenever I can. But sometimes things are out of your control. If you do want to convert between datetime2 and ticks inside SQL Server instead of letting the application handle it, then you need to do some date math. It can get a bit tricky avoiding arithmetic overflows and keeping things accurate: DateTime2 to Ticks

C system time nanoseconds, 5 milliseconds: 750,000 The Ticks property expresses date and time values in units of one ten-millionth of a second. For benchmarking, you want QueryPerformanceCounter. How to get accurate time (to 100 nano second) in C#?. C++11� Apparemment, StopWatch / QueryPerformanceCounter est le moyen d' aller, mais il ne peut être utilisé pour mesurer le temps, donc je pensais appeler DateTime.Now quand l'application démarre et puis juste avoir StopWatch courir et puis juste ajouter le temps écoulé de StopWatch à la valeur initiale retournée de DateTime.Now. Au moins ça

Microsecond timer for Windows, Use the QueryPerformanceCounter function to time events with a resolution of one microsecond. time; // For converting tick into real time // get the high resolution counter's accuracy Popular C++ topics at The Database Managers: C++ Tips� QueryPerformanceCounter in C#. Note: This is here just for information purposes. While you can use the performance counters on C#, the recomended way of measuring execution time. In C# (at least in C# 2.0) the QueryPerformance functions are not included so, before we can access them we need to import them from the kernel32.dll.

  • If you're measuring time intervals between parts of code, how is that any different from a timer? Either way, you can use interop to call the Kernel32.dll's QueryPerformanceCounter yourself.
  • Could you explain why you want to do this " to avoid using getters for its properties" does not make much of a reason. The problem with QueryPerformanceCounter is that it returns it's value in counts and the amount of counts per second is variable depending on architecture and can be found using QueryPerformanceFrequency. With a stopwatch you get value that is an actual unit of time.
  • @BenRobinson - it does a lot of sense to me otherwise I wont be asking.
  • @Bobb I have been an active member of stack overflow for a quite a while and i have to say that just because someone asks a question does not that it makes sense, is actually the right question or based on valid assumptions. We are not your subjects here to do your bidding, a bit of explanation of your reasoning can go along way towards solving your actual problem (which you have not explained) rather than just answering what may or may not be the wrong question.
  • this is open community. i have question and thats nothing to do with you being here for a while and you thinking of it is wrong or right. you dont have answer? please move along.
  • Yes I know. from all what I found on the web including the codeproject you are referring - it shows seconds and requires division by 'frequency'... My point of this question is actually to find out what is the value it returns and how can I use it without frequency. I am prepared to make it dependent to one particular setup without portability (dont care). Just need to understand what lpPerformanceCount actually is.
  • lpPerformanceCount is the number of ticks (is different for every system), lpFrequency is the number of ticks per second. To get the actual time, you would divide lpPerformanceCount by lpFrequency to get the amount in seconds. qpc(out time1); ...; qpc(out time2); long diff_in_ms = (time2-time1) * 1000 / frequency
  • Just to clarify, I mean the frequency is different for every system.
  • @Matthew, as for your formula -- why do you multiply the outcome by 1000? Since the frequency is ticks/second, you just need to multiply ticks by frequency to get the time span in seconds.
  • @astrowalker good point, the variable is called diff_in_ms though. I guess whatever I copied it from needed milliseconds.
  • DateTime.Ticks can also be used.
  • The best way to test that is to use Stopwatch.IsHighResolution
  • perhaps its useful for people who are not .net professionals. the point of measure performance is just that - measure performance. if your code waits on GC - it must be reflected in the stats.. this is not a scientific project.. if in practice your app is hitting GC when it shouldnt - thats the problem which must be a) discoverd (using the perfcounters I was asking) b) addressed by the dev (different story). thanks for idea on using kernel objects. but i dont think its a good idea, switching to kernel mode takes time and defies the essence of what i'd asked