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());
        }
Exemple #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();
            }
        }
Exemple #3
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();
        }
Exemple #4
0
        private static void CleanupRadioList_ThreadFunction()
        {
            // create a list to use to store radios to be removed
            List <Radio> remove_list = new List <Radio>();

            while (initialized)
            {
                _cleanupTimer.Stop();
                double current_time = _cleanupTimer.Duration;

                remove_list.Clear();

                lock (radio_list)
                {
                    foreach (Radio r in radio_list)
                    {
                        if (r == null)
                        {
                            continue;
                        }

                        // if the radio is updating, don't worry about whether we need to remove it
                        if (r.Updating)
                        {
                            continue;
                        }

                        // if the radio is connected, we will use ping+reply to make this decision
                        if (r.Connected)
                        {
                            continue;
                        }

                        // check when the last time that we received a discovery packet from this radio was, and add it to the remove list
                        // if it hasn't been seen lately
                        if (_radio_list_timed.ContainsKey(r.Serial) &&
                            current_time - _radio_list_timed[r.Serial] > RADIOLIST_TIMEOUT_SECONDS)
                        {
                            remove_list.Add(r); // we don't actually remove here since we are iterating through the list
                        }
                    }
                }

                // now loop through the remove list and take action
                foreach (Radio r in remove_list)
                {
                    RemoveRadio(r);
                    LogDisconnect("API::CleanupRadioList_ThreadFunction(" + r.ToString() + ")--Timeout waiting on Discovery");
                }

                Thread.Sleep(1000);
            }
        }
Exemple #5
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();
            }
        }
Exemple #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());
        }
Exemple #7
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();
        }
Exemple #8
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));
        }
Exemple #9
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);
            }
        }
Exemple #10
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);
        }
Exemple #11
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));
        }
Exemple #12
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);
 }
Exemple #13
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);
        }
        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);
        }
Exemple #15
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));
        }
Exemple #16
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);
        }
        //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;
        }
Exemple #18
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));
        }
Exemple #19
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);
        }
Exemple #20
0
        private void ProcessMessageThread()
        {
            ThreadProcessor.Auto();
            log.InfoFormat("开始对终端消息进行应答处理 {0}", Thread.CurrentThread.ManagedThreadId);
            Tuple <AsyncSocketConnection, TPKGHead> rd = null;
            HiPerfTimer timer = new HiPerfTimer();

            while (_isWorking)
            {
                if (ackQueue.TryDequeue(out rd) == false)//开始从对列中取接收到的数据进行处理
                {
                    Thread.Sleep(50);
                    continue;
                }
                try
                {
                    //服务端

                    timer.Start();
                    FireWaitHandle(rd.Item2);
                    var rs = PacketProcessorManager.DoProcess(rd.Item1, rd.Item2).GetAwaiter().GetResult();
                    if (rd.Item2.Flags.HasFlag(TPKGHeadFlags.CON))
                    {
                        PacketProcessorBase.SendCommonResponseMessage(rd.Item1, rd.Item2, rs == true ? 0 : 1);
                    }
                    timer.Stop();
                    packetCounts.AddOrUpdate(rd.Item2.CommandId, 1, (o, v) => ++ v);
                    packetTime.AddOrUpdate(rd.Item2.CommandId, timer.Duration, (o, v) => v + timer.Duration);
                    packetCounts30s.AddOrUpdate(rd.Item2.CommandId, 1, (o, v) => ++ v);
                    packetTime30s.AddOrUpdate(rd.Item2.CommandId, timer.Duration, (o, v) => v + timer.Duration);
                }
                catch (Exception ex)
                {
                    log.Error(ex);
                }
                Interlocked.Increment(ref processedMessageCount);
            }
        }
Exemple #21
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();
            }
        }
Exemple #22
0
        private void RefreshDataGrid()
        {
            dataGridView.Rows.Clear();
            if (textBox.Text.Length > 0)
            {
                timer.Start();
                searchManager.DoSearch(textBox.Text);
                timer.Stop();
                labelSearchTime.Text = "Search Time: " + String.Format("{0:0.###}", timer.Duration);

                if (timer.Duration < 0.25)
                {
                    labelSearchTime.ForeColor = Color.Green;
                }
                else if (timer.Duration >= 0.25 && timer.Duration < 0.5)
                {
                    labelSearchTime.ForeColor = Color.Blue;
                }
                else if (timer.Duration >= 0.5 && timer.Duration < 0.8)
                {
                    labelSearchTime.ForeColor = Color.SaddleBrown;
                }
                else
                {
                    labelSearchTime.ForeColor = Color.Red;
                }
            }
            else
            {
                labelSearchTime.Text      = "Search Time: ...";
                labelSearchTime.ForeColor = Color.Black;
            }
            if (dataGridView.Rows.Count > 0)
            {
                dataGridView.CurrentCell = dataGridView[0, 0];
            }
        }
Exemple #23
0
        public static int[] results(int agemin, int agemax, int relationship, int sign, int ethnicity, int eyes, int page, out string speed)
        {
            HiPerfTimer t           = new HiPerfTimer();
            int         startRecord = ((page - 1) * 15);
            int         stopRecord  = 15;


            IEnumerable <int> x = null;

            int[] xx = new int[16];

            SimpleSearchItem[][][] elementi;

            if (HttpContext.Current.Cache["SearchItems"] == null)
            {
                elementi = (SimpleSearchItem[][][])HttpContext.Current.Cache["SearchItemsBackup"];
            }
            else
            {
                elementi = (SimpleSearchItem[][][])HttpContext.Current.Cache["SearchItems"];
            }

            t.Start();


            //lock (thisLock)
            //{
            //xx = ((from a in elementi where a.age > agemin && a.age < agemax & a.relationship.Contains(relationship) && (sign == 0 || a.sign == sign) && a.ethnicity == ethnicity && (eyes == 0 || a.eyes == eyes) select a.userId).Skip(startRecord).Take(stopRecord)).ToArray();

            int foundrecords = 0;
            int counter      = 0;
            int z            = elementi.Count();
            int ss           = startRecord + stopRecord;

            for (int i = 0; i < z; i++)
            {
                SimpleSearchItem s = elementi[0][1][i];
                if (s.age > agemin && s.age < agemax)
                {
                    if (s.relationship.Contains(relationship) && (sign == 0 || s.sign == sign) && s.ethnicity == ethnicity)
                    {
                        if (foundrecords >= startRecord)
                        {
                            xx[counter] = s.userId;
                            counter     = counter + 1;
                        }
                        foundrecords = foundrecords + 1;

                        if (foundrecords > ss)
                        {
                            break;
                        }
                    }
                }
            }
            //}
            t.Stop();


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

            return(xx);
        }
Exemple #24
0
        static void Main(string[] args)
        {
            HiPerfTimer pt = new HiPerfTimer();

            pt.Start();
            MultiChartsWrapper multiCharts = new MultiChartsWrapper();

            List <string> dateList = new List <string>();
            List <string> dataList = new List <string>();

            using (var rd = new StreamReader("C:\\Users\\kartik\\Jupyter Notebooks\\MultiCharts\\input\\abc_k.csv"))
            {
                while (!rd.EndOfStream)
                {
                    var splits = rd.ReadLine().Split(',');
                    dateList.Add(splits[0]);
                    dataList.Add(splits[1]);
                }
            }

            dateList.RemoveAt(0);
            dataList.RemoveAt(0);

            int resultSize = 2900; // must be greater than rnn window(60)

            double[] input = Array.ConvertAll(dataList.Take(resultSize).ToArray(), new Converter <string, double>(Double.Parse));

            multiCharts.SetTrainingData(input);
            const int dateWidth     = 10;
            int       dateArraySize = resultSize * dateWidth;

            string[] dateArrayString = dateList.Take(resultSize).ToArray();

            long[] unixDateArray = new long[dateArrayString.Length];
            for (int i = 0; i < dateArrayString.Length; i++)
            {
                unixDateArray[i] = (Int64)(DateTime.Parse(dateArrayString[i]).Subtract(new DateTime(1970, 1, 1, 5, 30, 0))).TotalSeconds;
            }

            Console.WriteLine(unixDateArray.Length);
            Console.WriteLine(unixDateArray[0]);
            Console.WriteLine(input[1]);
            Console.WriteLine(input.Length);
            Console.WriteLine(dateArrayString[0].Length);
            multiCharts.SetDateArrayUNIX(unixDateArray);

            String fileName = "modelLSTM";

            Console.WriteLine(fileName);
            multiCharts.SetFileName(fileName);

            multiCharts.SetEpochs(30);
            multiCharts.SetLearningRate(0.001);
            multiCharts.SetScale(100);
            multiCharts.SetOptimizer(0);
            multiCharts.SetMomentum(10);

            Console.WriteLine("TRAIN");
            double res = multiCharts.TrainModel();

            Console.WriteLine(res);

            int testSize = 100; // must be greater than rnn window(60)

            double[] testSet = Array.ConvertAll(dataList.Skip(resultSize).Take(testSize).ToArray(), new Converter <string, double>(double.Parse));

            multiCharts.SetTestingData(testSet);

            int testDateArraySize = testSize * dateWidth;

            string[] testDateArrayString = dateList.Skip(resultSize).Take(testSize).ToArray();

            long[] unixTestDateArray = new long[testDateArrayString.Length];
            for (int i = 0; i < testDateArrayString.Length; i++)
            {
                unixTestDateArray[i] = (Int64)(DateTime.Parse(testDateArrayString[i]).Subtract(new DateTime(1970, 1, 1, 5, 30, 0))).TotalSeconds;
            }

            multiCharts.SetTestDateArrayUNIX(unixTestDateArray);

            Console.WriteLine("TEST");
            Console.WriteLine(multiCharts.TestModel());

            int ticks = 5;

            Console.WriteLine("PREDICT");
            double[] forecast = multiCharts.Predict(ticks);
            if (forecast != null)
            {
                for (int i = 0; i < ticks; i++)
                {
                    Console.WriteLine(forecast[i]);
                }
            }

            pt.Stop();
            Console.WriteLine("Duration : " + pt.Duration.ToString() + 's');
        }
Exemple #25
0
        public async Task RunTo(int stopPosition)
        {
            lock (this)
            {
                if ((this.SimulationTask != null) && !this.SimulationTask.IsCompleted)
                {
                    return;
                }

                this.BreakToken     = new CancellationTokenSource();
                this.SimulationTask = Task.Run(() =>
                {
                    this.CurrentInstruction = null;
                    AtmelProcessor.StartProfiling();
                    var timer = new HiPerfTimer();
                    Thread.CurrentThread.Priority = ThreadPriority.AboveNormal;
                    var audioEnabled       = this.AudioEnabled;
                    const double sliceTime = 1.0 / AudioPlayer.AudioSlices;
                    double fpsDuration     = 0;
                    double simDuration     = 0;
                    timer.Start();
                    if (audioEnabled)
                    {
                        AudioPlayer.Start();
                    }
                    while (!this.BreakToken.IsCancellationRequested)
                    {
                        // simulate cycles for one slice
                        var startCycles = AtmelContext.Clock;
                        var endCycles   = startCycles + AtmelProcessor.ClockSpeed / AudioPlayer.AudioSlices;

                        while (AtmelContext.Clock < endCycles)
                        {
                            AtmelProcessor.Step();
                            if (this.Breakpoints[AtmelContext.PC] || (AtmelContext.PC == stopPosition))
                            {
                                this.BreakToken.Cancel();
                                break;
                            }

#if PROFILE
                            // only do this once-per-instruction in profile build, it's really slow
                            if (this.BreakToken.IsCancellationRequested)
                            {
                                this.BreakToken.Cancel();
                                break;
                            }
#endif
                        }
                        timer.Stop();
                        var duration = timer.Duration;
                        timer.Restart();
                        fpsDuration      += duration;
                        simDuration      += duration;
                        this.TotalCycles += (endCycles - startCycles);
                        if (fpsDuration >= 1.0)
                        {
                            this.CyclesPerSecond = (int)(this.TotalCycles / fpsDuration);
                            this.TotalCycles     = 0;
                            fpsDuration          = 0;
                        }

                        // if audio is enabled then submit the buffer and wait until it starts playing
                        if (audioEnabled)
                        {
                            AudioPlayer.NextBuffer();
                        }

                        // otherwise sleep off any left-over time
                        else
                        {
                            var remaining = sliceTime - simDuration;
                            if (remaining >= 0)
                            {
                                Thread.Sleep((int)(1000 * remaining));
                            }
                            simDuration -= sliceTime;
                        }
                    }
                    if (audioEnabled)
                    {
                        AudioPlayer.Stop();
                    }
                    UpdateCurrentInstruction();
                    AtmelProcessor.ReportProfiling();
                });
            }

            await this.SimulationTask;
        }
Exemple #26
0
 public static void InterimTiming()
 {
     PreciseTimer.Stop();
     HPDuration += PreciseTimer.Duration;
     PreciseTimer.Start();
 } // end InterimTiming
Exemple #27
0
        /// <summary>
        /// Функция чтения
        /// </summary>
        /// <param name="dst">Ссылка на массив, в который записываются принятые байты.</param>
        /// <param name="index">Индекс в массиве, с которого начинается запись в массив.</param>
        /// <param name="count">Число байт для чтения.</param>
        /// <param name="result">Ссылка на строку, в которую записывается результат передачи.</param>
        /// <returns>Возвращает число прочитанных байт.</returns>
        public int Read(ref byte[] dst, int index, int count, ref string result)
        {
            if (!IsConnected)
            {
                Log("\tОшибка, порт закрыт...");
                result = m_spParams.Name + " закрыт.";
                return(0);
            }
            //
            result = "";
            //
            int uiTransmitted;

            //
            try
            {
                lock (m_syncObj)
                {
                    Log("Старт чтения порта ...");
                    int available = m_rxBuf.Lehgth;
                    if (available >= count)
                    {                     // в буфере есть все данные
                        Log("\tВ буфере есть все данные...");
                        if (dst == null)
                        {
                            dst = new byte[count];
                        }
                        uiTransmitted = m_rxBuf.GetRange(ref dst, index, count);
                        result        = uiTransmitted.ToString() + " bytes read.";
                        Log("Чтение завершено успешно.");
                        Log(dst, index, uiTransmitted);
                    }
                    else
                    {                     // в буфере либо нет ничего, либо не достаточно данных
                        Log("\tВ буфере не все данные (" + m_rxBuf.Lehgth.ToString() + " Б. ), ждем завершения приема...");
                        m_rdTimeoutTmr.Stop();
                        m_rdTimout = 0;
                        int waitCnt = count - m_rxBuf.Lehgth;
                        while (m_rdTimout < ReadTimeout)
                        {
                            m_rdTimeoutTmr.Start();
                            Thread.Sleep(1);
                            //byte[] rBuf = new byte[waitCnt];
                            //int rdLen = 0;
                            //try
                            //{
                            //	rdLen = m_serialPort.Read(rBuf, 0, waitCnt);
                            //	if (rdLen > 0)
                            //	{
                            //		m_rxBuf.PutRange(rBuf, 0, rdLen);
                            //	}
                            //}
                            //catch { }
                            m_rdTimeoutTmr.Stop();
                            m_rdTimout += ((m_rdTimeoutTmr.Duration * 1000));
                            if (m_rxBuf.Lehgth >= waitCnt)
                            {
                                break;
                            }
                        }
                        //
                        if (count > m_rxBuf.Lehgth)
                        {                         // Истек таймаут и не все данные приняты
                            if (m_rxBuf.Lehgth == 0)
                            {
                                Log("\tИстек таймаут ожидания, устройство не отвечает.");
                                uiTransmitted = 0;
                            }
                            else
                            {
                                Log("\tИстек таймаут ожидания, данные приняты не полностью.");
                                Log("\tПринято < " + m_rxBuf.Lehgth.ToString() + " Байт.>");
                                Log("\tКопируем то, что пришло.");
                                if (dst == null)
                                {
                                    dst = new byte[m_rxBuf.Lehgth];
                                }
                                uiTransmitted = m_rxBuf.GetRange(ref dst, index, m_rxBuf.Lehgth);
                                Log(dst, index, uiTransmitted);
                            }
                            result = "Таймаут ожидания < " + ReadTimeout.ToString() + "мс. > ( принято :" + uiTransmitted.ToString() + " bytes. )";
                        }
                        else
                        {                         // Все данные приняты
                            if (dst == null)
                            {
                                dst = new byte[count];
                            }
                            uiTransmitted = m_rxBuf.GetRange(ref dst, index, count);
                            result        = uiTransmitted.ToString() + " bytes read.";
                            Log("Чтение завершено успешно ( " + count.ToString() + " Б. )");
                            Log(dst, index, uiTransmitted);
                        }
                    }
                }
                //
                m_IsError = false;
                return(uiTransmitted);
            }
            catch (Exception ex)
            {
                m_IsError = true;
                result    = ex.Message;
                return(0);
            }
        }
Exemple #28
0
        public static void test()
        {
            string[]      vx = new string[1000];
            List <string> vy = new List <string>();

            for (int i = 0; i < vx.Length; i++)
            {
                vx[i] = "2";
                vy.Add("2");
            }

            HiPerfTimer o1 = new HiPerfTimer();
            HiPerfTimer o2 = new HiPerfTimer();

            o2.Start();
            for (int i = 0; i < vy.Count; i++)
            {
                string s = vy[i];
            }
            o2.Stop();
            o1.Start();
            for (int i = 0; i < vx.Length; i++)
            {
                string s = vx[i];
            }
            o1.Stop();



            string h1 = (o1.Duration * 1000000).ToString();
            string h2 = (o2.Duration * 1000000).ToString();



            HiPerfTimer  o  = new HiPerfTimer();
            PropertyItem bb = new PropertyItem();

            o.Start();
            PropertyItem[] hs = new PropertyItem[10];;
            //= new PropertyItem[10];
            //List<PropertyItem> ea = new List<PropertyItem>();

            hs = ia[3];

            o.Stop();
            //            ia = null;
            for (int i = 0; i < hs.Length; i++)
            {
            }
            string h = (o.Duration * 1000000).ToString();

            DatingApp.Models.User.Profile.Properties.Interests a = new DatingApp.Models.User.Profile.Properties.Interests();

            a.FreeTimeFavorite = new List <int> {
                1, 4, 5, 7
            };
            a.Hobbies = new List <int> {
                11, 14, 15, 17
            };
            a.Music = new List <int> {
                11, 14, 15, 17
            };
            a.Sport = new List <int> {
                11, 14, 15, 17
            };


            Dictionary <int, DatingApp.Models.User.Profile.Properties.Interests> aaa = new Dictionary <int, DatingApp.Models.User.Profile.Properties.Interests>();

            for (int i = 0; i < 500000; i++)
            {
                //HttpContext.Current.Cache.Insert(i.ToString(), a, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(30));
                //DatingEngine.InProcessCache.vsid.Add(i, "mucuc je šla na morje in je srečala starga mačkaa mucuc je šla na morje in je srečala starga mačkaa");
            }
            //HttpContext.Current.Cache.Insert("1s", aaa, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromDays(3));
        }
Exemple #29
0
        /// <summary>
        /// 获取脚本
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="tableName">表名</param>
        private string getInsertScript(string userName, string tableName)
        {
            statusString = "共计0条数据";
            StringBuilder      scriptText   = new StringBuilder();
            SqlHelper          sqlHelper    = new OracleHelper(Conn.ConnectionString, userName);
            string             sql          = string.Format("SELECT COLUMN_NAME AS COUMNNAME,DATA_TYPE AS TYPE,(CASE WHEN NULLABLE='Y' THEN 1 ELSE 0 END) AS ISN,DATA_LENGTH AS LENGTH FROM USER_TAB_COLUMNS WHERE TABLE_NAME='{0}' ORDER BY COLUMN_ID", tableName);
            List <TableStruct> tableStructs = new List <TableStruct>();
            var dt = sqlHelper.ExecuteDataTable(sql);

            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dataRow in dt.Rows)
                {
                    var tableStruct = new TableStruct();
                    tableStruct.coumnname  = dataRow["COUMNNAME"].ToString();
                    tableStruct.type       = dataRow["TYPE"].ToString();
                    tableStruct.isnullable = Convert.ToInt32(dataRow["ISN"]);
                    tableStruct.length     = Convert.ToInt16(dataRow["LENGTH"]);

                    tableStructs.Add(tableStruct);
                }

                var insertTmplete = getInsertTemplate(tableStructs, tableName);

                sql = String.Format("SELECT COUNT(1) AS DtSourceCount FROM {0} {1}", tableName, whereString);
                //数据行数,显示最多3000行,太多会内存溢出
                int dtSourceCount = 0;
                var dtCount       = sqlHelper.ExecuteDataTable(sql);
                if (dtCount.Rows.Count > 0)
                {
                    int.TryParse(dtCount.Rows[0][0].ToString(), out dtSourceCount);
                }

                sql = string.Format("SELECT * FROM {0} {1}", tableName, whereString);
                var dtSource = sqlHelper.ExecuteDataTable(sql);
                if (dtSource.Rows.Count > 0)
                {
                    //如果有clob类型字段,则申明变量
                    var clobStructs =
                        tableStructs.Where(i => lobTypes.Contains(i.type)).ToList();
                    if (clobStructs.Count > 0)
                    {
                        foreach (TableStruct clobStruct in clobStructs)
                        {
                            scriptText.Append("DECLARE V_" + clobStruct.coumnname + " NCLOB;\r\n");
                        }
                    }

                    bool hasBegin = false;
                    if (scriptText.Length > 0)
                    {
                        scriptText.Append("BEGIN\r\n");
                        hasBegin = true;
                    }

                    HiPerfTimer hiperTimer = new HiPerfTimer();
                    hiperTimer.Start();

                    //object lockObj = new object();
                    //Parallel.For(0, dtSource.Rows.Count, i =>
                    //{
                    //    var dataRow = dtSource.Rows[i];
                    //    var values = "";
                    //    foreach (TableStruct tableStruct in tableStructs)
                    //    {
                    //        if (dataTypes.Contains(tableStruct.type))
                    //        {
                    //            values += "TO_DATE('" + dataRow[tableStruct.coumnname] + "', 'yyyy-mm-dd hh24:mi:ss'),";
                    //        }
                    //        else if (lobTypes.Contains(tableStruct.type))
                    //        {
                    //            var varName = "V_" + tableStruct.coumnname;
                    //            values += varName + ",";
                    //            var varValue = "'" + dataRow[tableStruct.coumnname] + "'";

                    //            lock (lockObj)
                    //            {
                    //                scriptText.Append(varName + ":=" + varValue + ";\r\n");
                    //            }
                    //        }
                    //        else if (numberTypes.Contains(tableStruct.type))
                    //        {
                    //            if (DBNull.Value != dataRow[tableStruct.coumnname] &&
                    //                dataRow[tableStruct.coumnname].ToString() != "")
                    //            {
                    //                values += "'" + dataRow[tableStruct.coumnname] + "',";
                    //            }
                    //            else
                    //            {
                    //                if (tableStruct.isnullable == 0)
                    //                {
                    //                    values += "0,";
                    //                }
                    //                else
                    //                {
                    //                    values += "NULL,";
                    //                }
                    //            }
                    //        }
                    //        else
                    //        {
                    //            values += "'" + dataRow[tableStruct.coumnname] + "',";
                    //        }
                    //    }
                    //    values = values.Substring(0, values.Length - 1);

                    //    lock (lockObj)
                    //    {
                    //        scriptText.Append(string.Format(insertTmplete, values) + "\r\n");
                    //    }
                    //});

                    foreach (DataRow dataRow in dtSource.Rows)
                    {
                        var values = "";
                        foreach (TableStruct tableStruct in tableStructs)
                        {
                            if (dataTypes.Contains(tableStruct.type))
                            {
                                values += "TO_DATE('" + dataRow[tableStruct.coumnname] + "', 'yyyy-mm-dd hh24:mi:ss'),";
                            }
                            else if (lobTypes.Contains(tableStruct.type))
                            {
                                var varName = "V_" + tableStruct.coumnname;
                                values += varName + ",";
                                var varValue = "'" + dataRow[tableStruct.coumnname].ToString().Replace("'", "''") + "'";
                                scriptText.Append(varName + ":=" + varValue + ";\r\n");
                            }
                            else if (numberTypes.Contains(tableStruct.type))
                            {
                                if (DBNull.Value != dataRow[tableStruct.coumnname] &&
                                    dataRow[tableStruct.coumnname].ToString() != "")
                                {
                                    values += "'" + dataRow[tableStruct.coumnname] + "',";
                                }
                                else
                                {
                                    if (tableStruct.isnullable == 0)
                                    {
                                        values += "0,";
                                    }
                                    else
                                    {
                                        values += "NULL,";
                                    }
                                }
                            }
                            else
                            {
                                values += "'" + dataRow[tableStruct.coumnname] + "',";
                            }
                        }
                        values = values.Substring(0, values.Length - 1);

                        scriptText.Append(String.Format(insertTmplete, values) + "\r\n");
                    }

                    if (hasBegin)
                    {
                        scriptText.Append("END;");
                    }

                    hiperTimer.Stop();

                    statusString = "共计" + dtSourceCount + "条数据,取数" + dtSource.Rows.Count + "条用时:" + hiperTimer.Duration + "秒";
                }
            }

            return(scriptText.ToString());
        }
Exemple #30
0
        public void BackPropagationThead()
        {
            try
            {
                uint   compteur = 0;
                double erreur   = 100.0;
                double eta      = 0.90; // learning rate - controls the maginitude of the increase in the change in weights. found by trial and error.
                double alpha    = 0.04;

                byte   Label = 0;
                double dMSE;

                NeuroneSortieListe _memorizedNeuronOutputs = new NeuroneSortieListe();

                double[] VecteurEntree  = new double[841];
                double[] VecteurCible   = new double[10];
                double[] VecteurCourant = new double[10];

                //archive.Serialisation(_RNN);

                //while (erreur > 0.10 * 0.1 && _iEpochsCompleted < 40)
                while (_iEpochsCompleted < 70)
                {
                    // initialisation

                    for (int i = 0; i < 841; i++)
                    {
                        VecteurEntree[i] = 0.0;
                    }

                    for (int i = 0; i < 10; i++)
                    {
                        VecteurCible[i]   = 0.0;
                        VecteurCourant[i] = 0.0;
                    }

                    // Boucle
                    if (Definitions.mnistApprentissageDatabase.indexNextPattern == 0)
                    {
                        m_HiPerfTime.Start();
                        Definitions.mnistApprentissageDatabase.RandomizePatternSequence();
                    }
                    // Randomize pattern
                    // Pad 28 ==> 29

                    byte[] padImage = new byte[29 * 29];

                    //byte[][] padImage = new byte[29][];
                    //for (int i = 0; i < padImage.Length; ++i)
                    //    padImage[i] = new byte[29];


                    uint iPattern = BaseApprentissage.GetNextPattern();
                    Definitions.mnistApprentissageDatabase.result[iPattern].pixels.CopyTo(padImage, 0);
                    Label = Definitions.mnistApprentissageDatabase.result[iPattern].label;


                    // Label = BaseApprentissage.

                    for (int i = 0; i < 841; i++)
                    {
                        VecteurEntree[i] = 1.0;  // 1 Blanc et 0 noir
                    }
                    for (int hauteur = 0; hauteur < 28; ++hauteur)
                    {
                        for (int largeur = 0; largeur < 28; ++largeur)
                        {
                            VecteurEntree[1 + largeur + 29 * (hauteur + 1)] = (double)((int)(byte)padImage[largeur + 28 * hauteur]) / 128.0 - 1.0;
                            //VecteurEntree[1 + largeur + 29 * (hauteur + 1)] = (double)((int)(byte)padImage[hauteur][largeur]) / 128.0 - 1.0;
                        }
                    }

                    for (int i = 0; i < 10; i++)
                    {
                        VecteurCible[i] = -1.0;
                    }

                    VecteurCible[Label] = 1.0;

                    VecteurCourant = BackpropagateNeuralNet(VecteurEntree, VecteurCible, _memorizedNeuronOutputs, _form, this.Distorsion);

                    dMSE = 0.0;
                    for (int i = 0; i < 10; ++i)
                    {
                        dMSE += (VecteurCourant[i] - VecteurCible[i]) * (VecteurCourant[i] - VecteurCible[i]);
                    }
                    dMSE     /= 2.0;
                    _dMSE    += dMSE;
                    _dMSE200 += dMSE;

                    // Calcul seuil d'erreur
                    if (dMSE <= (0.10 * Convert.ToDouble(OCR.Properties.Settings.Default.EstimatedCurrentMSE)))
                    {
                        Backpropagate = false;
                    }
                    else
                    {
                        Backpropagate = true;
                    }

                    _nn++;
                    int    iBestIndex = 0;
                    double maxValue   = -99.0;

                    for (int i = 0; i < 10; ++i)
                    {
                        if (VecteurCourant[i] > maxValue)
                        {
                            iBestIndex = i;
                            maxValue   = VecteurCourant[i];
                        }
                    }

                    if (iBestIndex != Label)
                    {
                        erreurReconnaissances++;
                    }
                    else
                    {
                        bonneReconnaissances++;
                    }

                    // make step
                    string s = "";
                    if (_nn >= 200)
                    {
                        _dMSE200 /= 200;
                        erreur    = _dMSE200;
                        s         = "MSE:" + _dMSE200.ToString();

                        double partielpourcentage = ((float)erreurReconnaissances * 100) / (float)Definitions.mnistApprentissageDatabase.indexNextPattern;

                        _form.Invoke(_form._DelegateAddObject, new Object[] { 2, partielpourcentage });

                        _dMSE200 = 0;
                        _nn      = 0;
                    }

                    s = String.Format("{0} Miss Number:{1} Bonne reo {2}", Convert.ToString(Definitions.mnistApprentissageDatabase.indexNextPattern), erreurReconnaissances, bonneReconnaissances);
                    if (_form != null)
                    {
                        _form.Invoke(_form._DelegateAddObject, new Object[] { 5, s });
                    }

                    if (Definitions.mnistApprentissageDatabase.indexNextPattern >= nombre - 1)
                    {
                        m_HiPerfTime.Stop();
                        _dMSE /= Definitions.mnistApprentissageDatabase.indexNextPattern;
                        Definitions.mnistApprentissageDatabase.indexNextPattern = 0;

                        double pourcentage = ((float)erreurReconnaissances * 100) / (float)Definitions.mnistApprentissageDatabase.imageCount;

                        s = String.Format("Epochs:{0}, Pourcentage:{1}, Temps {2}, erreurs:{3} ",
                                          Convert.ToString(_iEpochsCompleted + 1), Convert.ToString(pourcentage), m_HiPerfTime.Duration, erreurReconnaissances.ToString());

                        if (_form != null)
                        {
                            _form.Invoke(_form._DelegateAddObject, new Object[] { 3, s });
                        }

                        erreurReconnaissances = 0;
                        bonneReconnaissances  = 0;
                        _iEpochsCompleted++;
                        Definitions.mnistApprentissageDatabase.indexNextPattern = 0;
                        _dMSE = 0;
                    }

                    compteur++;

                    if (Backpropagate == true)
                    {
                        Definitions.rnn.Backpropagate(VecteurCourant, VecteurCible, 0, _memorizedNeuronOutputs, nombreBackPropagation);
                    }
                }

                archive.Serialisation(Definitions.rnn);
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }
Exemple #31
0
        /// <summary>
        /// 获取脚本
        /// </summary>
        /// <param name="dbName">数据库名称</param>
        /// <param name="tableName">表名</param>
        private string getInsertScript(string dbName, string tableName)
        {
            StringBuilder      scriptText   = new StringBuilder();
            SqlHelper          sqlHelper    = new SqlServerHelper(CurConn.ConnectionString, dbName);
            string             sql          = String.Format("SELECT syscolumns.name AS coumnname ,systypes.name AS type,syscolumns.isnullable,syscolumns.length FROM syscolumns,systypes WHERE syscolumns.xusertype = systypes.xusertype AND syscolumns.id = OBJECT_ID('{0}') AND COLUMNPROPERTY( OBJECT_ID('[{0}]'),syscolumns.name,'IsIdentity') <> 1", tableName);
            List <TableStruct> tableStructs = new List <TableStruct>();
            var dt = sqlHelper.ExecuteDataTable(sql);

            if (dt.Rows.Count > 0)
            {
                HiPerfTimer hiperTimer = new HiPerfTimer();
                hiperTimer.Start();

                foreach (DataRow dataRow in dt.Rows)
                {
                    var tableStruct = new TableStruct();
                    tableStruct.coumnname  = dataRow["coumnname"].ToString();
                    tableStruct.type       = dataRow["type"].ToString();
                    tableStruct.isnullable = Convert.ToInt32(dataRow["isnullable"]);
                    tableStruct.length     = Convert.ToInt16(dataRow["length"]);

                    tableStructs.Add(tableStruct);
                }

                var insertTmplete = getInsertTemplate(tableStructs, tableName);

                sql = String.Format("SELECT COUNT(1) AS DtSourceCount FROM {0} {1}", tableName, whereString);
                //数据行数,显示最多3000行,太多会内存溢出
                int dtSourceCount = 0;
                var dtCount       = sqlHelper.ExecuteDataTable(sql);
                if (dtCount.Rows.Count > 0)
                {
                    int.TryParse(dtCount.Rows[0][0].ToString(), out dtSourceCount);
                }

                sql = String.Format("SELECT TOP 3000 * FROM {0} {1}", tableName, whereString);
                var dtSource = sqlHelper.ExecuteDataTable(sql);
                if (dtSource.Rows.Count > 0)
                {
                    //单线程,用于测试
                    //for (int i = 0; i < dtSource.Rows.Count; i++)
                    //{
                    //    var dataRow = dtSource.Rows[i];
                    //    var values = "";
                    //    foreach (TableStruct tableStruct in tableStructs)
                    //    {
                    //        if (numberTypes.Contains(tableStruct.type))     //数值类型处理
                    //        {
                    //            if (DBNull.Value != dataRow[tableStruct.coumnname] &&
                    //                dataRow[tableStruct.coumnname].ToString() != "")
                    //                values += "'" + dataRow[tableStruct.coumnname] + "',";
                    //            else
                    //            {
                    //                if (tableStruct.isnullable == 0)
                    //                {
                    //                    values += "'0',";
                    //                }
                    //                else
                    //                {
                    //                    values += "null,";
                    //                }
                    //            }
                    //        }
                    //        else if (tableStruct.type.ToUpper() == "UNIQUEIDENTIFIER")      //UNIQUEIDENTIFIER类型处理
                    //        {
                    //            var valueStr = dataRow[tableStruct.coumnname].ToString();
                    //            if (string.IsNullOrWhiteSpace(valueStr))
                    //            {
                    //                values += "CAST(NULL AS UNIQUEIDENTIFIER),";
                    //            }
                    //            else
                    //            {
                    //                values += string.Format("CAST('{0}' AS UNIQUEIDENTIFIER),", dataRow[tableStruct.coumnname].ToString());
                    //            }
                    //        }
                    //        else if (tableStruct.type.ToUpper() == "TIMESTAMP")
                    //        {
                    //            values += "DEFAULT,";
                    //        }
                    //        else
                    //        {
                    //            values += "'" + dataRow[tableStruct.coumnname].ToString().Replace("'", "''") + "',";
                    //        }
                    //    }
                    //    values = values.Substring(0, values.Length - 1);

                    //    scriptText.Append(String.Format(insertTmplete, values) + "\r\n");
                    //}

                    //多线程
                    object lockObj = new object();
                    Parallel.For(0, dtSource.Rows.Count, i =>
                    {
                        var dataRow = dtSource.Rows[i];
                        var values  = "";
                        foreach (TableStruct tableStruct in tableStructs)
                        {
                            if (numberTypes.Contains(tableStruct.type))     //数值类型处理
                            {
                                if (DBNull.Value != dataRow[tableStruct.coumnname] &&
                                    dataRow[tableStruct.coumnname].ToString() != "")
                                {
                                    values += "'" + dataRow[tableStruct.coumnname] + "',";
                                }
                                else
                                {
                                    if (tableStruct.isnullable == 0)
                                    {
                                        values += "'0',";
                                    }
                                    else
                                    {
                                        values += "null,";
                                    }
                                }
                            }
                            else if (tableStruct.type.ToUpper() == "UNIQUEIDENTIFIER")      //UNIQUEIDENTIFIER类型处理
                            {
                                var valueStr = dataRow[tableStruct.coumnname].ToString();
                                if (string.IsNullOrWhiteSpace(valueStr))
                                {
                                    values += "CAST(NULL AS UNIQUEIDENTIFIER),";
                                }
                                else
                                {
                                    values += string.Format("CAST('{0}' AS UNIQUEIDENTIFIER),", dataRow[tableStruct.coumnname].ToString());
                                }
                            }
                            else if (tableStruct.type.ToUpper() == "TIMESTAMP")     //TIMESTAMP类型处理,不能显示的插入值
                            {
                                values += "DEFAULT,";
                            }
                            else
                            {
                                values += "'" + dataRow[tableStruct.coumnname].ToString().Replace("'", "''") + "',";
                            }
                        }
                        values = values.Substring(0, values.Length - 1);

                        lock (lockObj)
                        {
                            scriptText.Append(String.Format(insertTmplete, values) + "\r\n");
                        }
                    });
                }

                hiperTimer.Stop();

                statusString = "共计" + dtSourceCount + "条数据,取数" + dtSource.Rows.Count + "条用时:" + hiperTimer.Duration + "秒";
            }

            return(scriptText.ToString());
        }