使用秒表测量时间紧迫的代码片段

时间:2018-11-05 13:05:03

标签: c# timer performance-testing stopwatch

因此,我正在尝试分析我编写的以下代码段:

private void Scrn_Timer_Tick(object sender, EventArgs e)
{
    watcher.Start();

    try
    {
        using (Bitmap bmpScreenshot = new Bitmap(Program.ScreenParameters.ScreenshotWidth, Program.ScreenParameters.ScreenshotHeight))
        {
            using (Graphics gfxScreenshot = Graphics.FromImage(bmpScreenshot))
            {
                gfxScreenshot.CopyFromScreen(Program.ScreenParameters.FromX, Program.ScreenParameters.FromY, 0, 0, size, CopyPixelOperation.SourceCopy);

                var rect = new Rectangle(0, 0, bmpScreenshot.Width, bmpScreenshot.Height);
                var data = bmpScreenshot.LockBits(rect, ImageLockMode.ReadWrite, bmpScreenshot.PixelFormat);
                var depth = Bitmap.GetPixelFormatSize(data.PixelFormat) / 8; //bytes per pixel

                var screenshotData = new byte[data.Width * data.Height * depth];

                //copy pixels to buffer
                //Marshal.Copy(data.Scan0, screenshotData, 0, screenshotData.Length);

                Parallel.ForEach(Program.slaveList, slave =>
                {
                    Marshal.Copy(data.Scan0, slave.image, 0, screenshotData.Length);
                    slave.Notify();
                });

                bmpScreenshot.UnlockBits(data);
            }
        }
    }
    catch(Exception ex)
    {
        logger.Debug(ex);
    }

    watcher.Stop();
    logger.Debug("Iteration-Time 'Scrn_Timer_Tick': " + watcher.Elapsed.TotalMilliseconds);
    watcher.Reset();
}

这是一个System.Timers.Timer,它每30毫秒计时一次。它生成一个屏幕截图,获取字节并将其分发给连接到我的系统的每个从站。 因此,我正在尝试评估整个过程,以了解我可以达到的FPS。我的秒表连续显示0到30毫秒之间的值,这非常好。但是我很恼火,因为我得到很多显示为0的测量值。 例如:

2018-11-05 13:56:59.9248 [16] DEBUG: Iteration-Time 'Scrn_Timer_Tick': 1,9086 
2018-11-05 13:56:59.9404 [19] DEBUG: Iteration-Time 'Scrn_Timer_Tick': 0 
2018-11-05 13:56:59.9716 [17] DEBUG: Iteration-Time 'Scrn_Timer_Tick': 0 
2018-11-05 13:57:00.0028 [15] DEBUG: Iteration-Time 'Scrn_Timer_Tick': 0 
2018-11-05 13:57:00.0496 [16] DEBUG: Iteration-Time 'Scrn_Timer_Tick': 10,9468 
2018-11-05 13:57:00.0652 [17] DEBUG: Iteration-Time 'Scrn_Timer_Tick': 10,9468 
2018-11-05 13:57:00.0964 [18] DEBUG: Iteration-Time 'Scrn_Timer_Tick': 0 
2018-11-05 13:57:00.1432 [22] DEBUG: Iteration-Time 'Scrn_Timer_Tick': 0,8427 
2018-11-05 13:57:00.1588 [19] DEBUG: Iteration-Time 'Scrn_Timer_Tick': 0,8427 
2018-11-05 13:57:00.1900 [18] DEBUG: Iteration-Time 'Scrn_Timer_Tick': 0 
2018-11-05 13:57:00.2368 [23] DEBUG: Iteration-Time 'Scrn_Timer_Tick': 7,0265 

在这种情况下,我无法得知秒表应该显示0。我的意思是,根据我的理解,测量点之间的处理始终至少运行,如果中止,我会捕捉到异常,但是我什么也没看到。 那么有人可以帮我解释一下这0次测量如何出现吗?

0 个答案:

没有答案