views:

366

answers:

2

I've just seen this question, where one of the answers indicates that System.Diagnostics.Stopwatch should only be used for diagnosing performance and not in production code.

In that case, what would be the best way to get precision timing in .NET. I'm currently in the early stages of building a very simple MIDI sequencer using the MIDI-out functionality of NAudio. I'd like to be able to send MIDI messages out aligned to (say) 1/10s with as little jitter as possible. Is this feasible, or will things like context-switching ruin my day?

I currently have some code in a console app that continuously calls Stopwatch and calculates the jitter when generating a stream of 1/16th-notes at 150bpm. The jitter is very low in this situation, however I'll be moving this off to another thread, so I dont know if that will remain the case.

+1  A: 

If you don't mind P/Invoke, you can use QueryPerformanceCounter: http://www.eggheadcafe.com/articles/20021111.asp

RichieHindle
+1. The performance counters will give you the most precise, lightest-weight counter you can find. It just isn't as straightforward as other implementations.
Adam Robinson
From what I understand, Stopwatch uses QueryPerformanceCounter if availble. I dont have anything against QPC and have used it in C++/Win32 apps before, however I dont know what goes on in the lower levels of the CLR so was wondering if there was a better way.
geofftnz
You're right, Stopwatch does use QueryPerformanceCounter - I hadn't realised. Having read the other question, I think the only reason someone recommended against using Stopwatch in production was that it carries some overhead, but I imagine that's quite small, and easily measured.
RichieHindle
+1  A: 

You could also use the native streaming MIDI API. I don't think its in NAudio but you could look at the C# Midi Toolkit to see if that one supports it. Otherwise you have two examples of how to do native MIDI API P/Invoke and can roll your own...

obiwanjacobi
there are some wrappers for the streaming MIDI APIs in NAudio, but they haven't been put through their paces yet. Still, might point you in the right direction
Mark Heath