Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 769
Aishwar Avatar asked Dec 31 '25 00:12

Aishwar


1 Answers

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.

like image 170
Mitch Wheat Avatar answered Jan 01 '26 13:01

Mitch Wheat