How to get ticks from QueryPerformanceCounter in C#?

后端 未结 6 1069
不知归路
不知归路 2020-12-21 01:22

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 e

6条回答
  •  一整个雨季
    2020-12-21 01:50

    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: pinvoke.net. 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.

    http://pinvoke.net/search.aspx?search=QueryPerformanceCounter&namespace=[All]

提交回复
热议问题