Timing a method and threads in .NET
I have two threads in my app - the main UI thread and another thread initiated by the wm_WiiMoteChanged event handler (a background thread). In the main thread I do some video processing. I have a function called processFrame
shown below. I use that code to measure the time to process each frame and thus the frames per second rate.
If I comment out the wm.WiiMoteChanged ...
line (see below), the frame rates are about 15-20 fps and looking at the video, this seems right (there is a small lag).
But when I uncomment the line, i.e. add the event handler (which will spawn a thread on its own), the fps goes up to 40-50, but this is definitely wrong - the video is in fact more laggy.
Can someone explain to me why this happens? Thanks.
private void Main_Load(object sender, EventArgs e)
{
try
{
开发者_如何转开发 wm.Connect();
//wm.WiimoteChanged += wm_WiimoteChanged;
wm.SetReportType(InputReport.IRAccel, true);
wm.SetLEDs(false, false, false, true);
}
catch (Exception x)
{
MessageBox.Show("Exception: " + x.Message);
this.Close();
}
}
More code:
private void processFrame(object sender, EventArgs e)
{
DateTime curr = DateTime.Now;
performOperation();
TimeSpan currTime = DateTime.Now - curr;
lblFPS.Text = (1000 / currTime.Milliseconds).ToString() + " fps";
}
EDIT
An interesting find, only when this line is present in wm_WiimoteChanged, does this happen.
ibxOutput.Image = new Image<Bgr, Byte>(_irViewAreaBitmap);
Sidenote: this line is the cause of the higher lag too - the processing done before setting this is actually fast!
Because by adding a event handler, you are responding to those WiimoteChanged
events and running extra code.
Does the handler contain locking? Suggest you post the code for wm_WiimoteChanged()
UPDATE: Suggest you use System.Diagnostics.Stopwatch
rather than DateTime.Now
It is likely that DateTime.Now is not accurate enough.
Okay, I'm being thick here, but I don't understand the frames per second calculation?
Should your FPS not actually be the number of times that ProcessFrame
is called in a second? If you measure that you might get a more accurate result.
Also, for measuring time, you're better off using StopWatch
; it's built for this purpose.
Does exactly one frame get rendered to the screen for each invocation of the processFrame
method? I suspect the rendering is happening elsewhere and is blocked by the code in the WiimoteChanged
handler, giving your processFrame
method more processor time.
For your FPS measurement to be accurate you need to ensure that processFrame
is called exactly once per frame. You should probably measure the time between subsequent invocations too rather than measuring the duration of performOperation
, unless processFrame
will be called immediately again when it returns.
精彩评论