Example #1
0
        public void GetJournalTextTest()
        {
            CodeTimer timer = new CodeTimer(typeof(CodeTimerTest), "GetJournalTextTest", true);

            timer.Stop();
            Assert.NotNull(timer.GetJournalText());
        }
        static void Main(string[] args)
        {
            var fileName = "source4compress.txt";
            var str      = File.ReadAllText(fileName);

            Console.WriteLine("SourceFileSize\t" + str.Length.ToString("N0"));

            var snappybin = SnappyCompress(str);
            var lz4bin    = LZ4Compress(str);
            var gzipbin   = GZipCompress(str);
            var zstdbin   = ZstdCompress(str, false, true);

            #region codetimer 测试代码性能
            CodeTimer.Initialize();

            var count = 100;

            CodeTimer.Time("SnappyCompress\t" + snappybin.Length.ToString("N0"), count, () => { SnappyCompress(str); });
            CodeTimer.Time("LZ4Compress\t" + lz4bin.Length.ToString("N0"), count, () => { LZ4Compress(str); });
            CodeTimer.Time("ZstdCompress\t" + zstdbin.Length.ToString("N0"), count, () => { ZstdCompress(str, false, true); });
            CodeTimer.Time("GZipCompress\t" + gzipbin.Length.ToString("N0"), count, () => { GZipCompress(str); });


            CodeTimer.Time("SnappyUnCompress", count, () => { SnappyUnCompress(snappybin); });
            CodeTimer.Time("LZ4UnCompress", count, () => { LZ4UnCompress(lz4bin); });
            CodeTimer.Time("ZstdUnCompress", count, () => { ZstdUnCompress(zstdbin); });
            CodeTimer.Time("GZipUnCompress", count, () => { GZipUnCompress(gzipbin); });


            #endregion

            Console.Read();
        }
Example #3
0
 public void CreateM4A()
 {
     try
     {
         double    totalTime  = 0.0;
         const int iterations = 1000;
         using (new CodeTimer("Combined"))
         {
             for (int i = 0; i < iterations; i++)
             {
                 CodeTimer timer = new CodeTimer();
                 using (timer)
                 {
                     File.Create(new LocalFileAbstraction("samples/sample.m4a"));
                 }
                 totalTime += timer.ElapsedTime.TotalSeconds;
             }
         }
         Console.WriteLine("Average time: {0}", totalTime / iterations);
     }
     catch (Exception e)
     {
         Console.WriteLine(e);
     }
 }
Example #4
0
        private static void TestStringBuilder()
        {
            int iteration = 100 * 1000;

            CodeTimer.Time("String  Concat", iteration,
                           () =>
            {
                var s = "1";
                for (int i = 1; i < 10; i++)
                {
                    s = s + "1";
                }
            }, Print);

            CodeTimer.Time("StringBuilder Concat", iteration,
                           () =>
            {
                var s = new StringBuilder();
                for (int i = 1; i < 10; i++)
                {
                    s.Append("1");
                }
            }, Print);

            ShowResult(result.ToString());
        }
Example #5
0
        /// <summary>计时,并用控制台输出行</summary>
        /// <param name="title">标题</param>
        /// <param name="times">次数</param>
        /// <param name="action">需要计时的委托</param>
        /// <param name="needTimeOne">是否需要预热</param>
        public static void TimeLine(String title, Int32 times, Action<Int32> action, Boolean needTimeOne = true)
        {
            var n = Encoding.Default.GetByteCount(title);
            Console.Write("{0}{1}:", n >= 16 ? "" : new String(' ', 16 - n), title);

            var timer = new CodeTimer();
            timer.Times = times;
            timer.Action = action;
            timer.ShowProgress = true;
#if !Android
            var currentForeColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Yellow;
            Int32 left = Console.CursorLeft;
#endif
            if (needTimeOne) timer.TimeOne();
            timer.Time();

            // 等一会,让进度那边先输出
            Thread.Sleep(10);
#if !Android
            Console.CursorLeft = left;
#endif
            Console.WriteLine(timer.ToString());
#if !Android
            Console.ForegroundColor = currentForeColor;
#endif
        }
Example #6
0
        public void DeserializerProtoBuf()
        {
            var s = _container.Resolve <IProtoBufferSerializer>();

            CodeTimer.Time("Protobuf", 10000, () =>
            {
                SSOToken token = new SSOToken();
                token.token    = Guid.NewGuid().ToString();
                token.custcode = "C001";
                token.timeout  = DateTime.Now;
                token.userid   = 1;
                var arry       = s.ToByteArray(token);
            });
            CodeTimer.Time("Json.net", 10000, () =>
            {
                SSOToken token = new SSOToken();
                token.token    = Guid.NewGuid().ToString();
                token.custcode = "C001";
                token.timeout  = DateTime.Now;
                token.userid   = 1;
                JsonConvert.SerializeObject(token);
            });
            var d = _container.Resolve <IProtoBufferDeserializer>();
            //var _token = d.FromByteArray<SSOToken>(arry);
            var str = "";
        }
Example #7
0
 public override void Test()
 {
     foreach (var item in Mappers)
     {
         CodeTimer.Time(item.Key, 100000, () => item.Value.Map());
     }
 }
Example #8
0
        public static long Run()
        {
            long      ran        = 0;
            const int Iterations = 1; // 100 * 1000 * 1000;

            var toFill = new byte[12];

            int[] values = { 100000, 9544, int.MaxValue - 1000 };

            CodeTimer.Time(true, "fixed", Iterations, () =>
            {
                for (int i = 0; i < values.Length; i++)
                {
                    WriteFixed((uint)values[i], toFill, i * 4);
                }
            });

            CodeTimer.Time(true, "managed", Iterations, () =>
            {
                for (int i = 0; i < values.Length; i++)
                {
                    WriteDirect((uint)values[i], toFill, i * 4);
                }
            });

            return(ran);
        }
Example #9
0
        public void SpeedTest()
        {
            TestClass test = new TestClass();

            test.Name      = "Jason Zander";
            test.Age       = 30;
            test.Employeed = false;
            test.Time      = new DateTime(2009, 1, 1);

            const int count = 1000;

            JsonSerializer.Serialize(test);

            JavaScriptSerializer serializer = new JavaScriptSerializer();

            serializer.Serialize(test);

            CodeTimer timer = CodeTimer.Start();

            for (int i = 0; i < count; i++)
            {
                string s = serializer.Serialize(test);
            }
            CodeTimer.WriteMilliseconds(timer);

            timer = CodeTimer.Start();

            for (int i = 0; i < count; i++)
            {
                string s = JsonSerializer.Serialize(test);
            }
            CodeTimer.WriteMilliseconds(timer);
        }
Example #10
0
        public void TimerEventTest()
        {
            CodeTimer timer = new CodeTimer(typeof(CodeTimerTest), "TimerEventTest", true);

            Assert.Equal("testEvent", timer.Event("testEvent").SubeventName);
            timer.Stop();
        }
Example #11
0
        public override Task OnCommand(string cmd)
        {
            var msgArgs = cmd.Split(new[] { ",", ";", " " }, StringSplitOptions.RemoveEmptyEntries);
            int repeat = 1, thread = 1;

            if (msgArgs.Length > 1)
            {
                repeat = msgArgs[1].CastTo(1);
            }
            if (msgArgs.Length > 2)
            {
                thread = msgArgs[2].CastTo(1);
            }
            var message = msgArgs[0];

            Task.Run(async() =>
            {
                var result = await CodeTimer.Time("netty", repeat, async() =>
                {
                    var data = message.Encode();
                    await _channel.WriteAndFlushAsync(data);
                }, thread);
                Console.WriteLine(result.ToString());
            });

            return(base.OnCommand(cmd));
        }
Example #12
0
        static long MeasureSearchMethods()
        {
            const int iterations = 1000000;

            long ran = 0;

            var source = new[]
            {
                "Connection",
                "KeepAlive",
                "TransferEncoding",
                "WwwAuthenticate",
                "Server"
            };

            Array.Sort(source, StringComparer.OrdinalIgnoreCase);

            var sortedSet = new SortedSet <string>(source, StringComparer.OrdinalIgnoreCase);

            var hashSet = new HashSet <string>(source);

            CodeTimer.Time(
                true,
                "binary search",
                iterations,
                () =>
            {
                if (Array.BinarySearch(source, "Server1", StringComparer.OrdinalIgnoreCase) != 0)
                {
                    ran += 1;
                }
            });

            CodeTimer.Time(
                true,
                "sorted set search",
                iterations,
                () =>
            {
                if (sortedSet.Contains("Server1", StringComparer.OrdinalIgnoreCase))
                {
                    ran += 1;
                }
            });

            CodeTimer.Time(
                true,
                "hash set search",
                iterations,
                () =>
            {
                if (hashSet.Contains("Server1", StringComparer.OrdinalIgnoreCase))
                {
                    ran += 1;
                }
            });

            return(ran);
        }
Example #13
0
 private static void ShowSplash()
 {
     CodeTimer.Time("ShowSplash", () =>
     {
         using (var form = new SplashForm())
             form.ShowDialog();
     });
 }
Example #14
0
 public void Test_Create()
 {
     CodeTimer.CodeExecuteTime(() =>
     {
         var result = ObjectIdGenerator.Current.Create();
         Output.WriteLine(result.ToString());
     });
 }
Example #15
0
        static void Test(IJsonProvider provider, object obj)
        {
            string json   = "";
            object newObj = null;

            CodeTimer.TimeLine(provider.GetType().Name + " - Serialize", 10 * 10000, i => json     = provider.Serialize(obj));
            CodeTimer.TimeLine(provider.GetType().Name + " - Deserialize", 10 * 10000, i => newObj = provider.Deserialize(json, obj.GetType()));
        }
Example #16
0
        public void ReflectionInvokeTest2()
        {
            var        obj = new InvokeMethod();
            MethodInfo m   = null;

            CodeTimer.Time("ReflectionInvoke.Create", CreateTimes, () => m = CreateMethodInfo(obj));
            CodeTimer.Time("ReflectionInvoke", InvokeTimes, () => ReflectionInvoke(m, obj));
        }
 static void FailHack()
 {
     CodeTimer.Time(true, "async void hack", Iterations, () =>
     {
         Task t = TestMethodFailureAsync();
         OnFaultOrSuccessAsyncHack(t, SuccessAction, "PUBLISH");
     });
 }
 static void FailHack2()
 {
     CodeTimer.Time(true, "async void hack2", Iterations, () =>
     {
         Task t = TestMethodFailureAsync();
         OnFaultOrSuccessAsyncHack2(t, FaultOrSuccessContinuationAction);
     });
 }
Example #19
0
 public static void Start(IRunner runner, RunType runType)
 {
     runner.Init(runType);
     CodeTimer.Time(
         runner.Name
         , Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["Iteration"] ?? "10000")
         , () => runner.Start());
 }
Example #20
0
        public void DelegateInvokeTest2()
        {
            var          obj = new InvokeMethod();
            Action <int> a   = null;

            CodeTimer.Time("DelegateInvokeTest.Create", CreateTimes, () => a = CreateDelegate(obj));
            CodeTimer.Time("DelegateInvokeTest", InvokeTimes, () => a.Invoke(InvokeTimes));
        }
Example #21
0
        /// <summary>
        /// Save new or modified item to data store
        /// </summary>
        /// <param name="address">the data address of the item, can be null if not available</param>
        /// <param name="data">the item to save</param>
        /// <param name="setOptions">list of options for saving, some may be custom</param>
        /// <returns>true if new record created</returns>
        public bool Set(Address address, object data, Dictionary <string, object> setOptions)
        {
            CodeTimer.MarkTime("Set START");
            var wasSet = Registered(data.GetType()).Set(address, data, setOptions);

            CodeTimer.MarkTime("Set END");
            return(wasSet);
        }
Example #22
0
        public void TestLogExcute(string logFromPath,
                                  string logToPath,
                                  Action <FileInfo, List <Tlog>, string> transfaseDataTable)
        {
            double move = 0, read = 0, zip = 0, del = 0;
            var    fileCount = 0;

            var total = CodeTimer.TimeLong("总共时间",
                                           1,
                                           () =>
            {
                string zipFileName  = DateTime.Now.ToString("yyyyMMddHHmm");
                string logToAbsPath = logToPath + "\\" + zipFileName;

                try
                {
                    // ReSharper disable once AccessToModifiedClosure
                    move = CodeTimer.TimeLong("移动数据", 1, () => FileUtil.MoveFolder(logFromPath, logToAbsPath, ref fileCount));

                    DirectoryInfo myFolder = new DirectoryInfo(logToAbsPath);
                    List <Tlog> tlogs      = new List <Tlog>();
                    read = CodeTimer.TimeLong("解析数据", 1, () =>
                    {
                        TraverseFolder2(myFolder, transfaseDataTable, tlogs, zipFileName);
                        TlogRepository.BulkInsertAll(tlogs);
                    }
                                              );

                    zip = CodeTimer.TimeLong("压缩数据",
                                             1,
                                             () =>
                    {
                        if (FileUtil.Zip(logToAbsPath, logToAbsPath + ".zip", ""))
                        {
                            del = CodeTimer.TimeLong("删除数据", 1, () => FileUtil.DeleteDir(logToAbsPath));
                        }
                    });
                    zip = zip - del;
                }
                catch (Exception e)
                {
                    string log = "解析数据出错,原因:[" + e + "、消息:" + e.Message + "]";
                    Console.WriteLine(@"	Err:	"+ e.Message);
                    WriteSysLog(log);
                }
            });

            OperationLogRepository.Insert(new OperationLog()
            {
                Num           = fileCount,
                MoveTimes     = move,
                ReadTimes     = read,
                ZipTimes      = zip,
                DeleteTimes   = del,
                TotalTimes    = total,
                OperationType = "TestLog"
            });
        }
Example #23
0
        public static long Run()
        {
            long      ran        = 0;
            const int iterations = 1000000;

            const string TransactionRowKeyPrefix = "__tx";

            ParameterExpression queryExpressionParameter       = Expression.Parameter(typeof(DynamicTableEntity));
            MemberExpression    partitionKeyPropertyExpression = Expression.Property(
                queryExpressionParameter,
                typeof(DynamicTableEntity).GetProperty(GetPropertyName <DynamicTableEntity>(x => x.PartitionKey)));
            MemberExpression rowKeyPropertyAccess = Expression.Property(
                queryExpressionParameter,
                typeof(DynamicTableEntity).GetProperty(GetPropertyName <DynamicTableEntity>(x => x.RowKey)));
            MethodInfo       stringCompareToMethodInfo       = typeof(string).GetMethod("CompareTo", new[] { typeof(string) });
            BinaryExpression filterTransactionRowsExpression = Expression.And(
                Expression.GreaterThan(
                    Expression.Call(rowKeyPropertyAccess, stringCompareToMethodInfo, Expression.Constant(TransactionRowKeyPrefix)),
                    Expression.Constant(0)),
                Expression.LessThan(
                    Expression.Call(rowKeyPropertyAccess, stringCompareToMethodInfo, Expression.Constant(TransactionRowKeyPrefix + ":")),
                    Expression.Constant(0)));

            Func <string, IEnumerable <string>, Expression <Func <DynamicTableEntity, bool> > > composeTargetedReadFilterEx =
                (partitionKey, rowKeys) =>
            {
                Expression eqFilter = null;
                foreach (string rowKey in rowKeys)
                {
                    BinaryExpression currentExpression = Expression.Equal(rowKeyPropertyAccess, Expression.Constant(rowKey));
                    eqFilter = eqFilter == null ? currentExpression : Expression.Or(eqFilter, currentExpression);
                }

                BinaryExpression result =
                    Expression.And(
                        Expression.Equal(
                            partitionKeyPropertyExpression,
                            Expression.Constant(partitionKey)),
                        Expression.Or(
                            eqFilter,
                            filterTransactionRowsExpression));
                return(Expression.Lambda <Func <DynamicTableEntity, bool> >(result, queryExpressionParameter));
            };

            CodeTimer.Time(true, "prebuilt", iterations, () =>
            {
                Expression <Func <DynamicTableEntity, bool> > exp = composeTargetedReadFilterEx("a", new[] { "1", "2" });
                if (exp.Body != null)
                {
                    ran++;
                }
            });

            CodeTimer.Time(true, "rebuilt", iterations, () => { ran = EvaluateRebuilt(TransactionRowKeyPrefix, ran); });

            return(ran);
        }
Example #24
0
        public void GenerateDelegateInvokeTest2()
        {
            JobAction a = null;

            CodeTimer.Time("Generate Delegate Create", CreateTimes, () => a = CreateDelegateAction());


            CodeTimer.Time("Generated Delegate InvokeTest", InvokeTimes, () => a(InvokeTimes));
        }
 public void Test_Create()
 {
     CodeTimer.Initialize();
     CodeTimer.CodeExecuteTime(() =>
     {
         var result = TimestampIdGenerator.Current.Create();
         Output.WriteLine(result.ToString());
     });
 }
 static void SuccessCW()
 {
     CodeTimer.TimeAsync(true, "success: ContinueWith", Iterations, () =>
     {
         Task t = TestMethodSuccessAsync();
         t.OnFaultOrSuccess(FaultOrSuccessContinuationAction);
         return(t);
     });
 }
Example #27
0
        public void Long64BitGeneratorTimeTest()
        {
            var id64Generator = new Id64Generator();

            CodeTimer.Time("生成随机", 10, () =>
            {
                id64Generator.Take(1000000).ToArray();
            });
        }
 static void SuccessAsync()
 {
     CodeTimer.TimeAsync(true, "success: async void", Iterations, () =>
     {
         Task t = TestMethodSuccessAsync();
         OnFaultOrSuccessAsync(t, SuccessAction, "PUBLISH");
         return(t);
     });
 }
 static void SyncHack2()
 {
     CodeTimer.TimeAsync(true, "sync success: async void hack2", Iterations, () =>
     {
         Task t = TestMethodSyncSuccessAsync();
         OnFaultOrSuccessAsyncHack2(t, FaultOrSuccessContinuationAction);
         return(t);
     });
 }
        public void TimeTest()
        {
            string name      = "Hello";     // TODO: Initialize to an appropriate value
            int    iteration = 1;           // TODO: Initialize to an appropriate value
            Action action    = DoSomeThing; // TODO: Initialize to an appropriate value

            CodeTimer.Time(name, iteration, action);
            // Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
Example #31
0
        static int MeasureTupleVsKeyValuePairInDictionaryLookup()
        {
            const int iterations = 1000000;

            int ran = 0;

            var tupleMap  = new DictionaryEx <Tuple <int, int, int, DateTime>, int>(200);
            var structMap = new DictionaryEx <StructTuple <int, int, int, DateTime>, int>(200);

            for (int i = 200 - 1; i >= 0; i--)
            {
                tupleMap.Add(new Tuple <int, int, int, DateTime>(400 - i, i + 1, i - 1, new DateTime(1990 + i % 10, 5, 2)), 0);
                structMap.Add(new StructTuple <int, int, int, DateTime>(400 - i, i + 1, i - 1, new DateTime(1990 + i % 10, 5, 2)), 0);
            }

            //CodeTimer.Time(true, "Tuple lookup",
            //    iterations,
            //    () =>
            //    {
            //        int value;
            //        if (tupleMap.TryGetValue(new Tuple<int, int, int, DateTime>(390, 11, 9, new DateTime(1990, 5, 2)), out value))
            //            ran += 1;
            //    });

            CodeTimer.Time(true, "Struct lookup outer add or update",
                           iterations,
                           () =>
            {
                var key = new StructTuple <int, int, int, DateTime>(390, 11, 9, new DateTime(1990, 5, 2));
                int a   = 1;
                int value;
                if (structMap.TryGetValue(key, out value))
                {
                    structMap[key] = value + a;
                }
                else
                {
                    structMap.Add(key, a);
                }
                ran += 1;
            });

            CodeTimer.Time(true, "Struct lookup AddOrUpdate",
                           iterations,
                           () =>
            {
                int a = 1;
                structMap.AddOrUpdate(
                    new StructTuple <int, int, int, DateTime>(390, 11, 9, new DateTime(1990, 5, 2)),
                    a,
                    (k, cv, nv) => cv + nv);
                ran += 1;
            });

            return(ran);
        }
Example #32
0
        /// <summary>
        /// 计时
        /// </summary>
        /// <param name="times">次数</param>
        /// <param name="action">需要计时的委托</param>
        /// <param name="needTimeOne">是否需要预热</param>
        /// <returns></returns>
        public static CodeTimer Time(Int32 times, Action<Int32> action, Boolean needTimeOne = true)
        {
            CodeTimer timer = new CodeTimer();
            timer.Times = times;
            timer.Action = action;

            if (needTimeOne) timer.TimeOne();
            timer.Time();

            return timer;
        }
Example #33
0
        /// <summary>
        /// Initalise the library, this is essentially the set method for <see cref="CurrentLibrary"/>
        /// </summary>
        /// <param name="current"></param>
        public void InitLibrary(SokoSolve.Core.Model.Library current)
        {
            using (CodeTimer timer = new CodeTimer("Library.InitLibray(...)"))
            {

                explorer.Clear();
                controller.Current = current;
                explorer.SyncDomain(new ItemLibrary(controller.Current));
                explorer.SyncUI();
                explorer.TreeView.ExpandAll();
            }
        }
        public void TestForCodeTimer()
        {
            var CachedProcessPriorityClass = Process.GetCurrentProcess().PriorityClass;
            var CachedThreadPriority = Thread.CurrentThread.Priority;

            using (var timer = new CodeTimer())
            {
                timer.Initialize();
                var result = timer.Time(1, () => { });
            }

            Assert.AreEqual(CachedProcessPriorityClass, Process.GetCurrentProcess().PriorityClass);
            Assert.AreEqual(CachedThreadPriority, Thread.CurrentThread.Priority);
        }
        protected SolverResult Solve(SokobanMap puzzle)
        {
            using (CodeTimer timer = new CodeTimer("TestSolver.Solve(...)"))
            {
                SolverController controller = new SolverController(puzzle);
                try
                {
                    System.Console.WriteLine(puzzle.ToString());

                    SolverResult results = controller.Solve();
                    if (results.Exception != null)
                    {
                        // Bubble up
                        throw new Exception("Solver Failed Iternally", results.Exception);
                    }

                    if (results.Status == SolverResult.CalculationResult.SolutionFound)
                    {
                        // Check that
                        Assert.IsTrue(results.HasSolution, "State says a solution was found, but none are listed in solutions list");
                    }

                    if (results.HasSolution)
                    {
                        int cc = 0;
                        foreach (Solution solution in results.Solutions)
                        {
                            string testRes = "Error";
                            Assert.IsTrue(solution.Test(puzzle, out testRes), testRes);
                            Console.WriteLine("Testing solution: {0} - {1}", cc, testRes);
                            cc++;
                        }
                    }

                    return results;
                }
                finally
                {
                    timer.Stop();
                    Console.WriteLine(controller.DebugReport.ToString(new DebugReportFormatter()));
                    System.Console.WriteLine("Total Time: " + timer.Duration(1));
                    System.Console.WriteLine("---");
                }
            }
        }
 public void CreateOgg()
 {
     try {
         double total_time = 0.0;
         int iterations = 1000;
         using(new CodeTimer("Combined")) {
             for(int i = 0; i < iterations; i++) {
                 CodeTimer timer = new CodeTimer();
                 using(timer) {
                     File.Create("samples/sample.ogg");
                 }
                 total_time += timer.ElapsedTime.TotalSeconds;
             }
         }
         Console.WriteLine("Average time: {0}", total_time / (double)iterations);
     } catch(Exception e) {
         Console.WriteLine(e);
     }
 }
Example #37
0
        /// <summary>
        /// 计时,并用控制台输出行
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="times">次数</param>
        /// <param name="action">需要计时的委托</param>
        /// <param name="needTimeOne">是否需要预热</param>
        public static void TimeLine(String title, Int32 times, Action<Int32> action, Boolean needTimeOne = true)
        {
            Console.Write("{0}{1}:", new String(' ', 16 - Encoding.Default.GetByteCount(title)), title);

            CodeTimer timer = new CodeTimer();
            timer.Times = times;
            timer.Action = action;
            timer.ShowProgress = true;

            ConsoleColor currentForeColor = Console.ForegroundColor;
            Console.ForegroundColor = ConsoleColor.Yellow;

            if (needTimeOne) timer.TimeOne();
            timer.Time();

            Console.WriteLine(timer.ToString());

            Console.ForegroundColor = currentForeColor;
        }
        public void TestReverseStrategyCoreSimple()
        {
            CodeTimer timer = new CodeTimer("");
            timer.Start();

            try
            {
                SokobanMap map = new SokobanMap();
                map.SetFromStrings(new string[]
                                   {
             "~##~#####",
              "##.##.O.#",
              "#.##.XO.#",
              "~##.X...#",
              "##.XP.###",
              "#.X..##~~",
              "#OO.##.##",
              "#...#~##~",
              "#####~#~~"
                                   });

                PuzzleMap pMap = new PuzzleMap((Puzzle)null);
                pMap.Map = map;

                SolverController controller = new SolverController(pMap);
                controller.Init();
                controller.State = SolverController.States.Running; // Manually set state, as we are not using the controller; but the strategy uses the controller to check if it should exit

                ReverseStrategy rev = new ReverseStrategy(controller);

                Evaluator<SolverNode> eval = new Evaluator<SolverNode>();
                EvalStatus result =  eval.Evaluate(rev);

                Assert.AreEqual(EvalStatus.CompleteSolution, result, "Should find a solution");
            }
            finally
            {
                timer.Stop();
                System.Console.WriteLine("Total Time: " + timer.Duration(1));
            }
        }
Example #39
0
        /// <summary>
        /// Timing simple regex usage in comparison to equivalent string operations.
        /// </summary>
        static void RegexVsStringOps()
        {
            var timer = new CodeTimer(50, 50);
            timer.OnMeasure += CodeTimer.PrintMeasure;

            var regex = new Regex(@".*(foo|bar|baz).*", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            var r = new Random();
            var strings = Enumerable.Range(0, 10)
                .Select(e => e % 3 == 0
                    ? RandomString(r, 100, "foo", "bar", "baz")
                    : RandomString(r, 100))
                .ToArray();

            timer.Measure("Regex version", () =>
            {
                var x = 0;
                for (int i = 0; i < strings.Length; i++)
                {
                    var i1 = regex.Match(strings[i]);
                    if (i1.Success)
                        x++;
                }
            });

            timer.Measure("StrOp version", () =>
            {
                var x = 0;
                for (int i = 0; i < strings.Length; i++)
                {
                    var str = strings[i].ToLower();
                    var i1 = str.IndexOf("foo");
                    var i2 = str.IndexOf("bar");
                    var i3 = str.IndexOf("baz");
                    if (i1 > 0 || i2 > 0 || i3 > 0)
                        x++;
                }
            });

        }
Example #40
0
 void IPostProcessor.Process(IMethodCallMessage callMsg, ref IMethodReturnMessage retMsg)
 {
     _timer = (CodeTimer)callMsg.Properties["codeTimer"];
     _timer.Finish();
 }
        /// <summary>
        /// Attempt to find a solution
        /// </summary>
        /// <returns>Solution class, or null which means no solution found</returns>
        public SolverResult Solve()
        {
            if (state != States.NotStarted) throw new Exception("Solve cannot be re-run on a single instance, this may cause state corruption.");

            if (staticAnalysis == null)
            {
                Init();
            }

            debugReport.AppendHeading(2, "Controller | Solving");

            SolverResult solverResult = new SolverResult();
            solverResult.DebugReport = debugReport;

            CodeTimer solveTime = new CodeTimer("Solver Timer");
            solveTime.Start();

            try
            {
                debugReport.Append("Solver starting");

                // Init
                state = States.Running;
                // Start the stats timer (per sec)
                stats.Start();

                // Prepare forward
                if (Thread.CurrentThread.Name == null)
                {
                    Thread.CurrentThread.Name = "FWD";
                }

                // Prepare and start reverse
                if (settings.UseReverseSolver)
                {
                    reverseWorker = new Thread(new ThreadStart(StartReverseWorker));
                    reverseWorker.Name = "REV";
                    reverseWorker.Priority = Thread.CurrentThread.Priority;
                    reverseWorker.Start();
                }

                // Start forward
                debugReport.AppendTimeStamp("Forward Started.");
                EvalStatus result = evaluator.Evaluate(strategy);
                if (state == States.Running)
                {
                    if (result == EvalStatus.CompleteSolution)
                    {
                        state = States.CompleteSolution;
                    }
                    else if (result == EvalStatus.CompleteNoSolution)
                    {
                        state = States.CompleteNoSolution;
                    }
                    else
                    {
                        state = States.CompleteNoSolutionInConstaints;
                    }
                }

                debugReport.AppendTimeStamp("Forward Complete. Status:{0}", result);

                // Wait for the reverse strategy to complete
                debugReport.AppendTimeStamp("Waiting for reverse to JOIN...");
                if (reverseWorker != null)
                {
                    reverseWorker.Join();
                }

                debugReport.AppendTimeStamp("Done.");

                // Rethrow on calling thread.
                if (reverseWorkerException != null) throw new Exception("Exception Throw by ReverseStrategy", reverseWorkerException);

                if (state == States.CompleteSolution)
                {
                    solverResult.Solutions = BuildSolutionPath();
                }

                if (state == States.Running)
                {
                    state = States.CompleteNoSolutionInConstaints;
                }

                // Exit

            }
            catch (Exception ex)
            {
                state = States.Error;
                debugReport.AppendException(ex);
                solverResult.Exception = ex;
            }
            finally
            {

                // Stop the timer
                stats.Stop();
                stats.EvaluationTime.AddMeasure(solveTime);
            }

            solverResult.ControllerResult = state;
            solverResult.Build(this);

            debugReport.CompleteSection();

            return solverResult;
        }
Example #42
0
 public static CodeTimer StartNew()
 {
     var timer = new CodeTimer();
     timer.Start();
     return timer;
 }
        /// <summary>
        /// Attempt to find a solution
        /// </summary>
        public EvalStatus Solve()
        {
            CodeTimer solveTime = new CodeTimer();
            solveTime.Start();

            try
            {
                debugReport.Append("Starting");
                IsEnabled = true;
                stats.Start();
                if (attempted) throw new Exception("Solve cannot be re-run on a single instance, this may cause state corruption.");
                attempted = true;
                EvalStatus result = evaluator.Evaluate(strategy);

                debugReport.AppendLabel("Complete", result.ToString());
                return result;
            }
            catch (Exception ex)
            {
                debugReport.Append(ex.Message);
                debugReport.Append(ex.StackTrace);
                throw new Exception("Solver failed.", ex);
            }
            finally
            {

                IsEnabled = false;
                stats.Stop();
                stats.EvaluationTime.AddMeasure(solveTime);
            }
        }
Example #44
0
 void IPreProcessor.Process(ref IMethodCallMessage msg)
 {
     _timer = new CodeTimer();
     msg.Properties.Add("codeTimer",_timer);
     _timer.Start(msg.MethodName);
 }
Example #45
0
 public void AddMeasure(CodeTimer timer)
 {
     count++;
     valueLast = (float)timer.Duration(count);
     valueTotal += valueLast;
 }
 public CodeTimerStatistic(Statistic stat)
 {
     this.stat = stat;
     timer = new CodeTimer(stat.Name);
     timer.Start();
 }