Пример #1
0
        public void SimpleTest()
        {
            var timer = new HiPerfTimer();

            // Initial duration is set to zero
            Assert.AreEqual(0, timer.Duration);

            timer.Start();

            // If we did not stop the timer, Duration sould be zero
            Assert.AreEqual(0, timer.Duration);

            timer.Stop();

            // After stop, Duration is > 0
            Assert.Less(0, timer.Duration);

            var lastTime = timer.Duration;

            // Duration should be the same as before
            Assert.AreEqual(lastTime, timer.Duration);

            timer.Stop();

            // Now it should be updated
            Assert.Less(lastTime, timer.Duration);

            timer.Start();

            // Should equals to zero
            Assert.AreEqual(0, timer.Duration);
            Assert.AreEqual("0 seconds", timer.ToString());
        }
Пример #2
0
        static void Main()
        {
            HiPerfTimer timer = new HiPerfTimer();

            foreach (Type day in Assembly.GetEntryAssembly().GetTypes()
                     .Where(x => x.IsInterface is false && typeof(IDay).IsAssignableFrom(x) && !x.Name.EndsWith("99") && x.Namespace.Contains("2021"))
                     .OrderByDescending(x => int.Parse(x.Name.Replace("Day", string.Empty))))
            {
                Console.WriteLine("=======================================");
                Console.WriteLine(day.Namespace + "." + day.Name);
                Console.WriteLine("=======================================");

                IDay puzzle = (IDay)Activator.CreateInstance(day);

                // Solve part 1
                string puzzleInput = "0";
                using (var webClient = new WebClient())
                {
                    webClient.Headers.Add(HttpRequestHeader.Cookie, "session=" + Environment.GetEnvironmentVariable("AoC-Session"));
                    var puzzleDay = day.Name.Replace("Day", string.Empty);
                    try
                    {
                        puzzleInput = webClient.DownloadString($"https://adventofcode.com/2021/day/{puzzleDay}/input");
                        puzzleInput = puzzleInput.Trim(' ', '\r', '\n');
                    }
                    catch
                    {
                        Console.WriteLine("Could not find puzzle input for " + day.Name);
                    }
                }

                Console.WriteLine("Example : " + puzzle.SolvePart1(puzzle.ExampleInput));
                timer.Start();
                long solutionPart1 = puzzle.SolvePart1(puzzleInput);
                timer.Stop();
                if (solutionPart1 > 0)
                {
                    TextCopy.ClipboardService.SetText(solutionPart1.ToString());
                }
                Console.WriteLine("Solution: " + solutionPart1);
                Console.WriteLine("Duration: " + timer.DurationFormatted);
                Console.WriteLine();

                Console.WriteLine("Example : " + puzzle.SolvePart2(puzzle.ExampleInput));
                timer.Start();
                long solutionPart2 = puzzle.SolvePart2(puzzleInput);
                timer.Stop();
                if (solutionPart2 > 0)
                {
                    TextCopy.ClipboardService.SetText(solutionPart2.ToString());
                }
                Console.WriteLine("Solution: " + solutionPart2);
                Console.WriteLine("Duration: " + timer.DurationFormatted);
                Console.WriteLine();

                Console.ReadKey();
                Console.WriteLine();
            }
        }
Пример #3
0
        private void ThreadRefreshStaHandler()
        {
            HiPerfTimer timer = new HiPerfTimer();

            System.Threading.Thread.Sleep(1000);

            int iStep = 0;

            while (true)
            {
                System.Threading.Thread.Sleep(1);
                switch (iStep)
                {
                case 0:
                {
                    timer.Start();
                    iStep = 10;
                }
                break;

                case 10:
                {
                    if (timer.TimeUp(1))
                    {
                        timer.Start();
                        for (int i = 0; i < 128; i++)
                        {
                            _bArrayInputSta[i] = true;
                        }
                        iStep = 20;
                    }
                }
                break;

                case 20:
                {
                    if (timer.TimeUp(1))
                    {
                        for (int i = 0; i < 128; i++)
                        {
                            _bArrayInputSta[i] = false;
                        }
                        iStep = 0;
                    }
                }
                break;

                default:
                    break;
                }
            }
        }
Пример #4
0
        static void Main()
        {
            HiPerfTimer timer = new HiPerfTimer();

            foreach (Type exercise in Assembly.GetEntryAssembly().GetTypes()
                     .Where(x => x.Name.StartsWith("Exercise3"))
                     .OrderByDescending(x => Int32.Parse(x.Name.Replace("Exercise", String.Empty))))
            {
                Console.WriteLine("===========================");
                Console.WriteLine(exercise.Name);
                Console.WriteLine("===========================");

                // Solve exercise
                timer.Start();
                var solution = exercise.InvokeMember("Solve", BindingFlags.InvokeMethod, null, null, null);
                timer.Stop();

                // Show solution
                Console.WriteLine("Solution: " + solution);
                Console.WriteLine("Duration: " + timer.DurationFormatted);
                Console.WriteLine();
                Console.ReadKey();
                Console.WriteLine();
            }
        }
Пример #5
0
        /// <summary>
        /// 获取条码
        /// </summary>
        /// <param name="m_strCurrentBarCode">条码</param>
        /// <returns></returns>
        private bool Get1DSN(ref string m_strCurrentBarCode)
        {
            string strRecieve = "";

            char[] charArray = new char[1];
            charArray[0] = ',';
            lock (lockObj)
            {
                try
                {
                    timeM.Start();
                    while (true)
                    {
                        try
                        {
                            if (bCodeReady)
                            {
                                strRecieve = strRemaid + strRecieve + serialPort.ReadExisting();
                                if (strRecieve.IndexOf("\r") > -1)
                                {
                                    //strRecieve = strRecieve.Trim();
                                    m_strCurrentBarCode = strRecieve.Substring(0, strRecieve.IndexOf("\r"));
                                    strRecieve          = strRecieve.Substring(strRecieve.IndexOf("\r") + 2);
                                    strRemaid           = strRecieve;
                                    RecieveMessageAction?.Invoke();
                                    break;
                                }
                                if (timeM.TimeUp(0.2))
                                {
                                    return(false);
                                }
                            }
                        }
                        catch
                        {
                            return(false);
                        }
                        System.Threading.Thread.Sleep(1);
                    }
                }
                catch
                {
                    return(false);
                }
            }
            return(true);
        }
Пример #6
0
        public static string CheckBoxListBtstsr(string propertyName, int columns, List <int> selectedValues)
        {
            HiPerfTimer a = new HiPerfTimer();
            HiPerfTimer b = new HiPerfTimer();


            int cultureId = Convert.ToInt32(System.Web.HttpContext.Current.Session["___APPCU"].ToString());

            a.Start();
            b.Start();
            List <PropertyItem> l = currentList(propertyName, cultureId, false);

            b.Stop();
            StringBuilder sb = new StringBuilder();

            sb.Append("<table style=\"text-align:left\"><tr>");
            for (int i = 0; i < l.Count; i++)
            {
                sb.Append("<td><input type=\"checkbox\" name=\"");
                sb.Append(propertyName);
                sb.Append("\" id=\"cbl");
                sb.Append(propertyName);
                sb.Append("_");
                sb.Append(i.ToString());
                sb.Append("\" value=\"");
                sb.Append(l[i].Value);
                sb.Append("\"");
                for (int j = 0; j < selectedValues.Count; j++)
                {
                    if (l[i].Value == selectedValues[j].ToString())
                    {
                        sb.Append(" checked=\"checked\" ");
                    }
                }
                sb.Append(" />&nbsp;<label class=\"input-sm\" for=\"cbl");
                sb.Append(propertyName);
                sb.Append("_");
                sb.Append(i.ToString());
                sb.Append("\">");
                sb.Append(l[i].Text);
                sb.Append("</label></td>");

                if (Math.IEEERemainder((i + 1), columns) == 0)
                {
                    sb.Append("</tr><tr>");
                }
            }
            sb.Append("</tr>");
            sb.Append("</table>");

            a.Stop();

            string a1 = (a.Duration * 1000000).ToString();

            string b1 = (b.Duration * 1000000).ToString();


            return(sb.ToString());
        }
Пример #7
0
        // End SetUpMPISubTimers

        public static void InterimTiming()
        {
            PreciseTimer.Stop();
            // Todo. revert to HiPerfTimer if necessary
//            HPDuration += PreciseTimer.Duration;
            HPDuration += PreciseTimer.Duration * 0.001;
            PreciseTimer.Start();
        }
Пример #8
0
        public bool ReadHeightValue(ref double m_dHeight)
        {
            string strReceive = string.Empty;

            string[] strArray;
            char[]   charArray = new char[1];
            string   strSend   = string.Empty;

            charArray[0] = ' ';
            lock (objLock)
            {
                try
                {
                    serialPort.ReadExisting();
                    strSend = m_cStx.ToString() + "MEASURE" + m_cEnd.ToString() + "\r\n";
                    serialPort.Write(strSend);
                    hptimer.Start();
                    strReceive = serialPort.ReadExisting();
                    while (true)
                    {
                        strReceive += serialPort.ReadExisting();
                        if (strReceive.IndexOf("\r\n") > -1)
                        {
                            strReceive     = strReceive.Trim();
                            strArray       = strReceive.Split(charArray, StringSplitOptions.RemoveEmptyEntries);
                            m_sHeightValue = strArray[1];
                            m_dHeight      = double.Parse(m_sHeightValue);
                            return(true);
                        }
                        if (hptimer.TimeUp(0.5))
                        {
                            this.adhereForm.Invoke(
                                new Action(() =>
                            {
                                LabelHeight.Text      = "Error";
                                LabelHeight.BackColor = Color.Red;
                            }
                                           )
                                );
                            return(false);
                        }
                    }
                }
                catch
                {
                    this.adhereForm.Invoke(
                        new Action(() =>
                    {
                        LabelHeight.Text      = "Error";
                        LabelHeight.BackColor = Color.Red;
                    }
                                   )
                        );
                    return(false);
                }
            }
        }
Пример #9
0
        static void Main(string[] args)
        {
            //精度 100纳秒
            HiPerfTimer pt = new HiPerfTimer();

            Console.ReadLine();

            pt.Start();
            //System.Threading.Thread.Sleep(100);           // 需要计时的代码
            int count = 5;

            pt.Stop();
            Console.WriteLine("HiPerfTimer duration: {0} sec", pt.Duration);
            Console.WriteLine("HiPerfTimer duration: {0} ms", pt.Duration * 1000);
            Console.WriteLine("HiPerfTimer duration: {0} μs", pt.Duration * 1000000);
            Console.WriteLine("HiPerfTimer duration: {0} ns", pt.Duration * 1000000000);

            Console.ReadLine();

            //精度 100纳秒
            // 若要为线程指定处理器关联,请使用 ProcessThread.ProcessorAffinity 方法。
            System.Diagnostics.Stopwatch myStopwatch = new System.Diagnostics.Stopwatch();
            myStopwatch.Start();
            //System.Threading.Thread.Sleep(100);           // 需要计时的代码
            int count2 = 5;

            myStopwatch.Stop();

            var elspsedSeconds = myStopwatch.ElapsedTicks / (decimal)System.Diagnostics.Stopwatch.Frequency;

            Console.WriteLine("Stopwatch duration: {0} sec", elspsedSeconds);
            Console.WriteLine("Stopwatch duration: {0} ms", elspsedSeconds * 1000);
            Console.WriteLine("Stopwatch duration: {0} μs", elspsedSeconds * 1000000);
            Console.WriteLine("Stopwatch duration: {0} ns", elspsedSeconds * 1000000000);

            Console.WriteLine("Stopwatch duration: {0} ms", myStopwatch.ElapsedMilliseconds);


            Console.ReadLine();

            //精度 秒
            var begintime = DateTime.Now.Ticks;
            //System.Threading.Thread.Sleep(100);           // 需要计时的代码
            int count3   = 5;
            var stoptime = DateTime.Now.Ticks;

            var costTicks = stoptime - begintime;

            Console.WriteLine("DateTime.Now.Ticks duration: {0} sec", costTicks / (double)10000000);
            Console.WriteLine("DateTime.Now.Ticks duration: {0} ms", costTicks / (double)10000);
            Console.WriteLine("DateTime.Now.Ticks duration: {0} μs", costTicks / (double)10);
            Console.WriteLine("DateTime.Now.Ticks duration: {0} ns", costTicks * (double)100);

            Console.ReadLine();
        }
Пример #10
0
        public bool ReadPressue(ref double PressureValue)
        {
            string strReceive = string.Empty;

            string[] strArray;
            char[]   charArray = new char[1];
            charArray[0] = ',';
            lock (lockObj)
            {
                try
                {
                    serialPort.ReadExisting();
                    serialPort.Write("READ\r\n");
                    hptimer.Start();
                    strReceive = serialPort.ReadExisting();
                    while (true)
                    {
                        strReceive += serialPort.ReadExisting();
                        if (strReceive.IndexOf("\r\n") > -1)
                        {
                            strReceive         = strReceive.Trim();
                            strArray           = strReceive.Split(charArray, StringSplitOptions.RemoveEmptyEntries);
                            m_strPressureValue = strArray[2];
                            PressureValue      = double.Parse(m_strPressureValue);
                            break;
                        }
                        if (hptimer.TimeUp(0.5))
                        {
                            this.adhereForm.Invoke(
                                new Action(() =>
                            {
                                labelPressure.Text      = "Error";
                                labelPressure.BackColor = Color.Red;
                            }
                                           )
                                );
                            return(false);
                        }
                    }
                }
                catch
                {
                    this.adhereForm.Invoke(
                        new Action(() =>
                    {
                        labelPressure.Text      = "Error";
                        labelPressure.BackColor = Color.Red;
                    }
                                   )
                        );
                    return(false);
                }
            }
            return(true);
        }
Пример #11
0
        private Tuple <FrameInfo, Stream> PreloadFile(FrameInfo frameInfo)
        {
            // TODO: Consider using CopyStreamToStreamAsync from TPL extensions
            var timer = new HiPerfTimer();

            timer.Start();

            var    filename          = frameInfo.Filename;
            var    bufferSize        = frameInfo.BufferSize;
            var    cancellationToken = frameInfo.Token;
            Stream memoryStream      = null;
            var    buffer            = FMemoryPool.ManagedPool.GetMemory(bufferSize);

            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                using (var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, FileOptions.SequentialScan))
                {
                    var length = fileStream.Length;
                    memoryStream = FMemoryPool.StreamPool.GetStream((int)length);
                    //memoryStream.Position = 0;

                    while (fileStream.Position < length)
                    {
                        cancellationToken.ThrowIfCancellationRequested();

                        int numBytesRead = fileStream.Read(buffer, 0, buffer.Length);
                        memoryStream.Write(buffer, 0, numBytesRead);
                    }

                    memoryStream.Position = 0;
                }
            }
            catch (OperationCanceledException)
            {
                // That's fine
            }
            catch (Exception e)
            {
                // Log the exception
                FLogger.Log(e);
            }
            finally
            {
                // Put the buffer back in the pool so other blocks can use it
                FMemoryPool.ManagedPool.PutMemory(buffer);
            }

            timer.Stop();
            frameInfo.DurationIO = timer.Duration;

            return(Tuple.Create(frameInfo, memoryStream));
        }
Пример #12
0
        /// <summary>
        /// Функция передачи массива байт
        /// </summary>
        /// <param name="buf">Массив для пердачи.</param>
        /// <param name="index">Индекс в массиве, с которого начинаеися передача.</param>
        /// <param name="count">Количество байт для передачи.</param>
        /// <param name="result">Ссылка на строку, в которую записывается результат передачи.</param>
        /// <returns>Возвращает количество переданных байт.</returns>
        public int Write(byte[] buf, int index, int count, ref string result)
        {
            result = "";
            //
            Log("Старт записи...");
            if (!IsConnected)
            {
                Log("\tОшибка, порт закрыт...");
                result = m_spParams.Name + " закрыт.";
                return(0);
            }
            //
            HiPerfTimer tmr  = new HiPerfTimer();
            double      time = 0;
            bool        err  = false;

            try
            {
                lock (m_syncObj)
                {
                    tmr.Start();
                    m_serialPort.Write(buf, index, count);
                    m_serialPort.BaseStream.Flush();
                    tmr.Stop();
                    time = tmr.Duration * 1000;
                    if (WriteTimeout != System.IO.Ports.SerialPort.InfiniteTimeout)
                    {
                        if ((time + 10) > WriteTimeout)
                        {
                            err = true;
                            throw new TimeoutException("Ошибка: Истекло время передачи ( " + WriteTimeout.ToString() + " мс. )");
                        }
                    }
                    result    = count.ToString() + " bytes written.";
                    m_IsError = false;
                    Log("\tЗаписано " + count.ToString() + " Байт.");
                    Log(buf, index, count);
                }
                //
                return(count);
            }
            catch (Exception ex)
            {
                result = ex.Message;
                if (!err)
                {
                    m_IsError = true;
                }
                //
                Log(ex.Message);
                return(0);
            }
        }
Пример #13
0
        private Frame PreloadFrame(Tuple <FrameInfo, Stream> tuple)
        {
            var timer = new HiPerfTimer();

            timer.Start();

            var frameInfo         = tuple.Item1;
            var stream            = tuple.Item2;
            var cancellationToken = frameInfo.Token;

            var frame = new Frame(
                frameInfo,
                CreateTexture,
                UpdateTexture,
                DestroyTexture);

            var cleanupStream = false;

            try
            {
                cancellationToken.ThrowIfCancellationRequested();
                frameInfo.Decoder = FrameDecoder.Create(frameInfo.Filename, CreateTextureForDecoder, FMemoryPool, stream);
            }
            catch (OperationCanceledException)
            {
                // That's fine, just make sure to cleanup
                cleanupStream = true;
            }
            catch (Exception e)
            {
                // Log the exception
                FLogger.Log(e);
                // And don't forget to cleanup
                cleanupStream = true;
            }
            finally
            {
                // We're done with this frame, put used memory stream back in the pool
                if (stream != null && cleanupStream)
                {
                    FMemoryPool.StreamPool.PutStream(stream);
                }
            }

            timer.Stop();
            frameInfo.DurationTexture = timer.Duration;

            return(frame);
        }
Пример #14
0
        private ToolResult ApplyMetrology(HMetrologyModel hMetrology, int index, string measureName)
        {
            HiPerfTimer timer = new HiPerfTimer();

            timer.Start();
            try
            {
                hMetrology.ApplyMetrologyModel(Image);
                double   circleCenterRow, circleCenterCol, radius;
                HTuple   circleResult = hMetrology.GetMetrologyObjectResult(new HTuple(index), new HTuple("all"), new HTuple("result_type"), new HTuple("all_param"));
                HXLDCont circleXLD    = hMetrology.GetMetrologyObjectResultContour(new HTuple("all"), new HTuple("all"), new HTuple(1.5));
                HXLDCont modelXLD     = hMetrology.GetMetrologyObjectMeasures(index, "all", out HTuple Row, out HTuple Col);

                if (circleResult.Length < 3)
                {
                    return(new ToolResult()
                    {
                        ResultName = measureName, Errormessage = "圆形测量失败", GetResultTime = DateTime.Now, IsSuccess = false
                    });
                }
                circleCenterRow = circleResult[0].D;
                circleCenterCol = circleResult[1].D;
                radius          = circleResult[2].D;
                if (info.IsShowResult)
                {
                    Window.SetColor("blue");
                    circleXLD.DispXld(Window.Window);
                }
                if (info.IsShowFindRegion)
                {
                    Window.SetColor("green");
                    Window.DisplayCircle(info.ToolName, info.CircleRow, info.CircleCol, info.CircleRadius, true);
                }
                hMetrology.ClearMetrologyObject(new HTuple(index));
                return(new ToolResult()
                {
                    ResultName = measureName, ImageX = circleCenterCol, ImageY = circleCenterRow, ImageRadius = radius, GetResultTime = DateTime.Now, ElapsedTime = timer.Duration, IsSuccess = true
                });
            }
            catch (Exception e)
            {
                WriteErrorLog("VisionTool", e.ToString());
                return(new ToolResult()
                {
                    ResultName = measureName, Errormessage = e.ToString(), GetResultTime = DateTime.Now, IsSuccess = false
                });
            }
        }
Пример #15
0
        public void TestParsing()
        {
            HiPerfTimer handRolledTimer = new HiPerfTimer();

            handRolledTimer.Start();

            for (int i = 0; i < EVALUATION_COUNT; i++)
            {
                OPathParser.Parse(EXPRESSION);
            }

            handRolledTimer.Stop();

            Console.WriteLine("Hand-rolled parsing did {0} in {1:0.000} millis",
                              EVALUATION_COUNT, (handRolledTimer.Duration * 1000));
        }
        protected PointD m_TrackingVPos; // virtual position

        #endregion Fields

        #region Constructors

        public VirtualMousePosition(System.Drawing.Point startPosition)
        {
            m_StartPos = startPosition;

            // real position
            m_LastPhysicalPos = startPosition;
            m_CurPhysicalPos = startPosition;

            // virtual position
            m_TrackingVPos = new PointD( startPosition.X, startPosition.Y );
            m_LastVPos = new PointD(startPosition.X, startPosition.Y);

            m_LastTime = Environment.TickCount;
            m_Timer = new HiPerfTimer();
            m_Timer.Start();
        }
Пример #17
0
        private void ResetDown()
        {
            if (MainModule.FormMain.bAuto)
            {
                return;
            }
            //   resetTimer.Start();
            resetTimer.Start();
            //  MainModule.FormMain.bResetPress = false;
            if (startHoming)
            {
                return;
            }
            if (resetTimer.TimeUp(2))
            {
                DateSave.Instance().Production.IsStop = false;
                bJetTestStart  = false;
                jetTestStep    = -1;
                bMarkTestStart = false;
                markTestStep   = -1;
                //  Program.ccdStationA.Clear();
                Program.num = 0;
                MainModule.FormMain.bEstop = false;
                //if (IOManage.INPUT("ESTOP").On)
                //{

                DateSave.Instance().Production.StationMaterial = false;//工位有无料标志
                // }
                //  MainControls.StationMaterial = false;//工位有无料标志


                //   m_FeederTask.taskInfo.iTaskStep = 0;
                //    m_FeederTask.taskInfo.bTaskOnGoing = false;
                //m_MarkTask.taskInfo.iTaskStep = 0;
                //  m_MarkTask.taskInfo.bTaskOnGoing = false;
                //   m_TransferTask.taskInfo.iTaskStep = 0;
                //   m_TransferTask.taskInfo.bTaskOnGoing = false;
                //  m_JetTask.taskInfo.iTaskStep = 0;
                //  m_JetTask.taskInfo.bTaskOnGoing = false;
                MainControls.taskInfo.iTaskStep    = 0;
                MainControls.taskInfo.bTaskOnGoing = false;

                ControlPlatformLib.Global.logger.Info("长按复位:" + DateTime.Now.ToString("yyyy/MM/dd/ HH : mm : ss"));
            }
        }
        public void Start()
        {
            var timer = new HiPerfTimer();

            _mapper.Initialize();
            _mapper.Map();

            timer.Start();

            for (int i = 0; i < 1000000; i++)
            {
                _mapper.Map();
            }

            timer.Stop();

            Console.WriteLine("{0}: - {1} - Mapping time: \t{2}s", _mapper.Name, _mode, timer.Duration);
        }
Пример #19
0
        public static bool RetryUntilTrueWithTimeout(Func <bool> callable, double timeoutMs)
        {
            var    hiPerfTimer = new HiPerfTimer();
            double remaining;

            do
            {
                hiPerfTimer.Start();
                Thread.Sleep(1000);
                if (callable())
                {
                    return(true);
                }
                hiPerfTimer.Stop();
                remaining = timeoutMs - hiPerfTimer.DurationDouble;
            } while (remaining > 0);
            return(false);
        }
Пример #20
0
 public void WhileTrue(Action callable, long timeoutMs)
 {
     _task = Task.Factory.StartNew(() =>
     {
         var hiPerfTimer = new HiPerfTimer();
         while (!this._cts.IsCancellationRequested)
         {
             hiPerfTimer.Start();
             callable();
             hiPerfTimer.Stop();
             double remain = timeoutMs - hiPerfTimer.DurationDouble;
             if (remain > 0)
             {
                 Thread.Sleep((int)(remain));
             }
         }
     }, TaskCreationOptions.LongRunning);
 }
Пример #21
0
        public void TestOPathPerformance()
        {
            HiPerfTimer rawTimer = new HiPerfTimer();

            rawTimer.Start();

            for (int i = 0; i < EVALUATION_COUNT; i++)
            {
                OPathExpression opathExpression = OPathExpression.Compile(EXPRESSION);

                OPathDocument opathDocument = new OPathDocument();
                opathDocument.Add("listDictionary", m_ListDictionary);

                OPathNavigator opathNavigator = OPathNavigator.CreateNavigator(opathDocument);

                opathNavigator.Evaluate(opathExpression);
            }

            rawTimer.Stop();

            Console.WriteLine("Uncompiled OPath performance {0} evaluations in {1:0.000} millis",
                              EVALUATION_COUNT, (rawTimer.Duration * 1000));

            HiPerfTimer cachedTimer = new HiPerfTimer();

            cachedTimer.Start();

            OPathExpression cachedOPathExpression = OPathExpression.Compile(EXPRESSION);

            for (int i = 0; i < EVALUATION_COUNT; i++)
            {
                OPathDocument opathDocument = new OPathDocument();
                opathDocument.Add("listDictionary", m_ListDictionary);

                OPathNavigator opathNavigator = OPathNavigator.CreateNavigator(opathDocument);

                opathNavigator.Evaluate(cachedOPathExpression);
            }

            cachedTimer.Stop();

            Console.WriteLine("Compiled OPath performance {0} evaluations in {1:0.000} millis",
                              EVALUATION_COUNT, (cachedTimer.Duration * 1000));
        }
Пример #22
0
        }   // End LeftPrintFixedInteger

        public static void InitializeTiming(int InputNumberofTimers)
        {
            NumberofSubTimings = InputNumberofTimers;
            SubTimers          = new HiPerfTimer[NumberofSubTimings]; // Timing Objects
            SubDurations       = new double[NumberofSubTimings];      // Hold partial timing
            SubTimingEnable    = new bool[NumberofSubTimings];
            SubTimingNames     = new string[NumberofSubTimings];

            for (int itimer = 0; itimer < NumberofSubTimings; itimer++)
            {
                SubTimers[itimer]       = new HiPerfTimer();
                SubDurations[itimer]    = 0.0;
                SubTimingEnable[itimer] = true;
            }
            PreciseTimer = new HiPerfTimer();
            PreciseTimer.Start();

            startTime = DateTime.Now; // Set the initial time.
        }                             // End InitializeTiming
Пример #23
0
        public static ResultType RetryUntilTrueWithTimeout(Func <ResultType> callable, double timeoutMs)
        {
            var    hiPerfTimer = new HiPerfTimer();
            double remaining;

            do
            {
                hiPerfTimer.Start();
                Thread.Sleep(1000);
                var callableResultType = callable();
                if (callableResultType != ResultType.Continue)
                {
                    return(callableResultType);
                }
                hiPerfTimer.Stop();
                remaining = timeoutMs - hiPerfTimer.DurationDouble;
            } while (remaining > 0);
            return(ResultType.Timeout);
        }
Пример #24
0
        private bool GetData(ref string m_hight)
        {
            string strRecieve = "";

            char[] charArray = new char[1];
            charArray[0] = ',';
            lock (lockObj)
            {
                try
                {
                    timeM.Start();
                    while (true)
                    {
                        try
                        {
                            strRecieve = strRemaid + strRecieve + serialPort.ReadExisting();
                            if (strRecieve.IndexOf("\r") > -1)
                            {
                                //strRecieve = strRecieve.Trim();
                                m_hight    = strRecieve.Substring(0, strRecieve.IndexOf("\r"));
                                strRecieve = strRecieve.Substring(strRecieve.IndexOf("\r") + 2);
                                strRemaid  = strRecieve;
                                break;
                            }
                            if (timeM.TimeUp(1))
                            {
                                return(false);
                            }
                        }
                        catch
                        {
                            return(false);
                        }
                        System.Threading.Thread.Sleep(1);
                    }
                }
                catch
                {
                    return(false);
                }
            }
            return(true);
        }
Пример #25
0
        //private static void HandleUsersByLastVisit()
        //{
        //    CacheItemRemovedCallback removalOrderByLastVisit;
        //    removalOrderByLastVisit = new CacheItemRemovedCallback(UsersByLastVisitRemoved);

        //    SearchListGenerator g = new SearchListGenerator();
        //    OrderItem[] o = g.UsersByLastVisit;


        //    HttpRuntime.Cache.Insert("ByLastVisit", o, null, DateTime.UtcNow.AddSeconds(OrderTimeInterval), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Normal, removalOrderByLastVisit);
        //    HttpRuntime.Cache.Insert("ByLastVisitBackup", o, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration);

        //    SearchItem[] elementi = (SearchItem[])HttpRuntime.Cache["SearchItems"];
        //    OrderItem[] ox = (OrderItem[])HttpRuntime.Cache["ByLastVisit"];
        //    OrderItem[] ox2 = (OrderItem[])HttpRuntime.Cache["ByLastVisitBackup"];

        //    var x = from a in elementi join ee in ox on a.userId equals ee.UserId where a.age > 18 && a.age < 99 & a.relationship.Contains(5) && (a.sign == 1) && a.ethnicity == 170 && (a.eyes == 70) orderby ee.Row ascending select a.userId;
        //    var x2 = from a in elementi join ee in ox2 on a.userId equals ee.UserId where a.age > 18 && a.age < 99 & a.relationship.Contains(5) && (a.sign == 1) && a.ethnicity == 170 && (a.eyes == 70) orderby ee.Row ascending select a.userId;

        //    SearchEngine.counter = SearchEngine.counter + 1;
        //}

        private static void HandleSearchItems()
        {
            HiPerfTimer t = new HiPerfTimer();

            CacheItemRemovedCallback removalSearchItems;

            removalSearchItems = new CacheItemRemovedCallback(SearchItemsRemoved);

            t.Start();
            SearchListGenerator g = new SearchListGenerator();

            SimpleSearchItem[][][] o = g.SimpleSearchCache();
            t.Stop();

            timer = (t.Duration * 1000000).ToString();

            HttpRuntime.Cache.Insert("SearchItems", o, null, DateTime.Now.AddSeconds(ReloadTimeInterval), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.Normal, removalSearchItems);
            HttpRuntime.Cache.Insert("SearchItemsBackup", o, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration);
            SearchEngine.counter = SearchEngine.counter + 1;
        }
Пример #26
0
        internal CodeReaderRes ReadByRS232(out string strRecv, int iTimeout)
        {
            strRecv = string.Empty;
            if (!bInitOk)
            {
                return(CodeReaderRes.INITFAIL);
            }
            HiPerfTimer hiPerfTimer = new HiPerfTimer();
            string      strTemp     = "";

            lock (_objLock)
            {
                try
                {
                    _port.ReadExisting();
                    System.Threading.Thread.Sleep(1);
                    _port.Write(codeReaderData.strTriggerCmd + "\r\n");
                    System.Threading.Thread.Sleep(1);
                    strTemp = _port.ReadExisting();
                    hiPerfTimer.Start();
                    while (true)
                    {
                        strTemp += _port.ReadExisting();
                        if (strRecv.Contains(codeReaderData.strEndCode))
                        {
                            strRecv = strTemp;
                            return(CodeReaderRes.SUCCESS);
                        }
                        if (hiPerfTimer.TimeUp(iTimeout))
                        {
                            return(CodeReaderRes.TIMEOUT);
                        }
                        System.Threading.Thread.Sleep(10);
                    }
                }
                catch (Exception)
                {
                    return(CodeReaderRes.ERROR);
                }
            }
        }
Пример #27
0
        internal CodeReaderRes ReadByTcpClient(out string strRecv, bool bAsync, int iTimeout)
        {
            strRecv      = string.Empty;
            _strRecvData = string.Empty;
            try
            {
                if (null == codeReaderData || null == _tcpClient || !_tcpClient.IsConnected)
                {
                    return(CodeReaderRes.INITFAIL);
                }
                if (!_tcpClient.Send(codeReaderData.strTriggerCmd + "\r\n"))
                {
                    return(CodeReaderRes.ERROR);
                }
                if (bAsync)
                {
                    return(CodeReaderRes.SUCCESS);
                }

                //sync
                HiPerfTimer hiPerfTimer = new HiPerfTimer();
                hiPerfTimer.Start();
                while (true)
                {
                    if (!string.IsNullOrEmpty(_strRecvData))
                    {
                        break;
                    }
                    if (hiPerfTimer.TimeUp((double)((double)iTimeout / 1000.0)))
                    {
                        return(CodeReaderRes.TIMEOUT);
                    }
                }
                strRecv = _strRecvData;
                return(CodeReaderRes.SUCCESS);
            }
            catch (Exception)
            {
                return(CodeReaderRes.ERROR);
            }
        }
Пример #28
0
        /// <summary>
        /// 电芯进站校验
        /// </summary>
        /// <param name="strSFC">Barcode</param>
        /// <returns>OK - MES return =0 </returns>
        /// <returns>NG - MEW return >0 </returns>
        public MESRes CheckSfcStatus(string strSFC)
        {
            MESRes      mesRes       = new MESRes();
            string      strStartTime = "";
            string      strEndTime   = "";
            HiPerfTimer hTimer       = new HiPerfTimer();

            mesRes.bSuccess  = false;
            mesRes.strErrMsg = "调用失败";
            try
            {
                hTimer.Start();
                strStartTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ssfff");
                string strUser     = DataManage.StrValue(DataGroups.DataGroupMESCheckSfcParam, DataItemMESCheckSfcParam.User);
                string strPassword = DataManage.StrValue(DataGroups.DataGroupMESCheckSfcParam, DataItemMESCheckSfcParam.Password);
                int    iTimeout    = DataManage.IntValue(DataGroups.DataGroupMESCheckSfcParam, DataItemMESCheckSfcParam.TimeOut);
                miCheckSFCStatusService.Credentials = new NetworkCredential(strUser, strPassword);
                iTimeout = (iTimeout < 10 || iTimeout > 60000) ? 10000 : iTimeout;
                miCheckSFCStatusService.Timeout = iTimeout;

                changeStatusRequest.site              = DataManage.StrValue(DataGroups.DataGroupMESCheckSfcParam, DataItemMESCheckSfcParam.site);              //设备所在站点
                changeStatusRequest.operation         = DataManage.StrValue(DataGroups.DataGroupMESCheckSfcParam, DataItemMESCheckSfcParam.operation);         //工位
                changeStatusRequest.operationRevision = DataManage.StrValue(DataGroups.DataGroupMESCheckSfcParam, DataItemMESCheckSfcParam.operationRevision); //工位版本
                changeStatusRequest.sfc = strSFC;                                                                                                              //电芯号

                miCheckSFCsta.ChangeSFCStatusRequest = changeStatusRequest;
                miCheckSFCstatusRes    = miCheckSFCStatusService.miCheckSFCstatus(miCheckSFCsta);
                mesRes.miCheckResponse = miCheckSFCstatusRes;
                mesRes.bSuccess        = true;
            }
            catch (Exception ex)
            {
                mesRes.bSuccess  = false;
                mesRes.strErrMsg = ex.ToString();
            }
            strEndTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ssfff");
            int iTime = (int)(hTimer.Duration * 1000);

            MESLog.WriteMiCheckSfcStatusLog(miCheckSFCsta, mesRes, strStartTime, strEndTime, iTime);
            return(mesRes);
        }
Пример #29
0
        public void TestNativePerformance()
        {
            HiPerfTimer nativeTimer = new HiPerfTimer();

            nativeTimer.Start();

            for (int i = 0; i < EVALUATION_COUNT; i++)
            {
                bool result =
                    //m_ListDictionary.Count > 0;
                    //m_ListDictionary["Key1"] != null;
                    m_ListDictionary["Key1"][0].Length == 6;
                //(m_ListDictionary["Key1"][0].Trim().Length * 2)
                //    == (m_ListDictionary["Key2"][0].Trim().Length + m_ListDictionary["Key3"][0].Trim().Length);
            }

            nativeTimer.Stop();

            Console.WriteLine("Native performance {0} evaluations in {1:0.000} millis",
                              EVALUATION_COUNT, (nativeTimer.Duration * 1000));
        }
Пример #30
0
        private ToolResult ApplyMetrology(HMetrologyModel hMetrology, int index, string measureName)
        {
            HiPerfTimer timer = new HiPerfTimer();

            timer.Start();
            try
            {
                //window.DisplayImage(image);
                hMetrology.ApplyMetrologyModel(Image);
                ///获取直线的中心坐标
                ///lineresult 为获取到的直线起点与终点坐标
                double lineCenterRow, lineCenterCol, angle;
                HTuple lineResult = hMetrology.GetMetrologyObjectResult(new HTuple("all"), new HTuple("all"), new HTuple("result_type"), new HTuple("all_param"));

                lineCenterRow = (lineResult[0].D + lineResult[2]).D / 2;
                lineCenterCol = (lineResult[1].D + lineResult[3]).D / 2;
                //获取直线测量矩形
                angle = HMisc.LineOrientation(lineResult[0].D, lineResult[1].D, lineResult[2].D, lineResult[3].D);
                angle = TransAngle.HuToAngle(angle);
                hMetrology.ClearMetrologyObject(new HTuple(index));

                Window.DisplaySingleLine(info.ToolName, lineResult[0].D, lineResult[1].D, lineResult[2].D, lineResult[3].D, true, "blue");
                if (info.IsShowFindRegion)
                {
                    Window.DisplayRectangle2(info.ToolName, info.Rectangle2Row, info.Rectangle2Col, info.Rectangle2Angle, info.Rectangle2Length1, info.Rectangle2Length2, true);
                }
                return(new ToolResult()
                {
                    ResultName = measureName, ImageX = lineCenterCol, ImageY = lineCenterRow, ImageAngle = angle, GetResultTime = DateTime.Now, ElapsedTime = timer.Duration, IsSuccess = true
                });
            }
            catch (Exception e)
            {
                WriteErrorLog("VisionTool", e.ToString());
                return(new ToolResult()
                {
                    ResultName = measureName, Errormessage = e.ToString(), GetResultTime = DateTime.Now, IsSuccess = false
                });
            }
        }
Пример #31
0
        public void WhileTrue(Action callable, int retryCount, long timeoutMs, long loopSleepMs = 0)
        {
            int currentCount = 0;

            _task = Task.Factory.StartNew(() =>
            {
                var hiPerfTimer = new HiPerfTimer();
                while (!this._cts.IsCancellationRequested)
                {
                    hiPerfTimer.Start();
                    callable();
                    currentCount++;
                    Thread.Sleep((int)loopSleepMs);
                    hiPerfTimer.Stop();
                    double remain = timeoutMs - hiPerfTimer.DurationDouble;
                    if (remain <= 0 || currentCount >= retryCount)
                    {
                        _cts.Cancel();
                    }
                }
            }, TaskCreationOptions.LongRunning);
        }
Пример #32
0
        public static void RunProfiling()
        {
#if DEBUG
            Console.WriteLine("You are running in DEBUG mode, results are unreliable");
#endif
            List <Func <T> > funcs = new List <Func <T> >();
            funcs.Add(TestDirect);
            funcs.Add(TestInlineable);
            funcs.Add(TestStaticLambda);
            funcs.Add(TestLocalLambda);
            funcs.Add(TestCompiledLambda);
            funcs.Add(TestVirtualFunctionCall);
            funcs.Add(TestStructConstraint);
            funcs.Add(TestStructConstraintInstance);
            funcs.Add(TestStructConstraintIndirection);

            HiPerfTimer timer = new HiPerfTimer();

            foreach (Func <T> k in funcs)
            {
                Console.WriteLine("Profiling " + k.Method.Name + " with " + typeof(T).FullName + " ...");
                double[] times = new double[REPETITIONS];
                for (int i = 0; i < REPETITIONS; i++)
                {
                    timer.Start();
                    k();
                    timer.Stop();
                    times[i] = timer.Duration;
                }

                Console.WriteLine("Avg: {0},\tMax: {1}\tMin: {2}",
                                  times.Sum() / REPETITIONS,
                                  times.Max(),
                                  times.Min()
                                  );
                Console.WriteLine();
            }
        }
Пример #33
0
 private void btnConnect_Click(object sender, EventArgs e)
 {
     if (btnConnect.Text.Equals("Connect"))
     {
         try
         {
             if (null == driver)
             {
                 throw new Exception();
             }
             HiPerfTimer hTimer = new HiPerfTimer();
             driver.Init(codeReaderData);
             hTimer.Start();
             while (true)
             {
                 if (driver.IsConnected())
                 {
                     break;
                 }
                 if (hTimer.TimeUp(2))
                 {
                     break;
                 }
             }
             if (!driver.IsConnected())
             {
                 MessageBox.Show("Failure to connected to code reader " + codeReaderData.Name, "", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
             }
         }
         catch (Exception)
         {
             MessageBox.Show("Failure to connected to code reader " + codeReaderData.Name, "", MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification);
         }
     }
     else
     {
     }
 }