private static void Main(string[] args) { Stopwatch s1 = new Stopwatch(); s1.Start(); double serialPi = SerialEstimationOfPi(); s1.Stop(); System.Console.WriteLine("Serial: {0}", s1.ElapsedMilliseconds); s1.Reset(); s1.Start(); double naiveParallelPi = NaiveParallelPi(); s1.Stop(); System.Console.WriteLine("Naive Parallel: {0}", s1.ElapsedMilliseconds); s1.Reset(); s1.Start(); double parallelpi = ParallelPi(); s1.Stop(); System.Console.WriteLine("Parallel: {0}", s1.ElapsedMilliseconds); s1.Reset(); s1.Start(); double parallelPartitionerPi = ParallelPartitionerPi(); s1.Stop(); System.Console.WriteLine("Parallel with partitioner: {0}", s1.ElapsedMilliseconds); }
private static void Main() { // Testing different type of reverse algorithms Stopwatch timeTest = new Stopwatch(); Console.Write("Enter some string: "); string str = Console.ReadLine(); // Using StringBuilder timeTest.Start(); string reversed = ReverseSB(str); timeTest.Stop(); Console.WriteLine("Reverse text: {0}\ntime: {1} - StringBuilder class", reversed, timeTest.Elapsed); timeTest.Reset(); Console.WriteLine(); // Using Array.Reverse timeTest.Start(); string reversedArrayReverse = ReverseArray(str); timeTest.Stop(); Console.WriteLine("Reverse text: {0}\ntime: {1} - Array.Reverse", reversedArrayReverse, timeTest.Elapsed); timeTest.Reset(); Console.WriteLine(); // Using XOR timeTest.Start(); string reversedXor = ReverseXor(str); timeTest.Stop(); Console.WriteLine("Reverse text: {0}\ntime: {1} - XOR", reversedXor, timeTest.Elapsed); timeTest.Reset(); }
private void Form1_Load(object sender, EventArgs e) { asdassd.Add("MenuGetir", () => new MyClass()); Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 1000000; i++) { MyClass c = new MyClass(); } sw.Stop(); MessageBox.Show(sw.ElapsedMilliseconds.ToString()); sw.Reset(); Type t = typeof(MyClass); sw.Start(); for (int i = 0; i < 1000000; i++) { var c = System.Activator.CreateInstance(Type.GetType(t.FullName)); } sw.Stop(); MessageBox.Show(sw.ElapsedMilliseconds.ToString()); sw.Reset(); sw.Start(); for (int i = 0; i < 1000000; i++) { var c = asdassd["MenuGetir"](); } sw.Stop(); MessageBox.Show(sw.ElapsedMilliseconds.ToString()); }
public void WillThrottleCalls() { var locker = GetLockProvider(); if (locker == null) return; // sleep until start of throttling period Thread.Sleep(DateTime.Now.Ceiling(_period) - DateTime.Now); var sw = new Stopwatch(); sw.Start(); for (int i = 0; i < 5; i++) locker.AcquireLock("test"); sw.Stop(); _output.WriteLine(sw.Elapsed.ToString()); Assert.True(sw.Elapsed.TotalSeconds < 1); sw.Reset(); sw.Start(); var result = locker.AcquireLock("test", acquireTimeout: TimeSpan.FromMilliseconds(250)); sw.Stop(); Assert.Null(result); _output.WriteLine(sw.Elapsed.ToString()); sw.Reset(); sw.Start(); result = locker.AcquireLock("test", acquireTimeout: TimeSpan.FromSeconds(4)); sw.Stop(); Assert.NotNull(result); _output.WriteLine(sw.Elapsed.ToString()); }
public void ComputeTimesPrimes() { Stopwatch w = new Stopwatch(); w.Start(); PrimeNumbers.GeneratePrimeNumbers1(100000); Console.WriteLine("Primes 1: " + w.ElapsedMilliseconds.ToString()); w.Stop(); w.Reset(); w.Start(); PrimeNumbers.GeneratePrimeNumbers2(100000); Console.WriteLine("Primes 2: "+ w.ElapsedMilliseconds.ToString()); w.Stop(); w.Reset(); w.Start(); PrimeNumbers.GeneratePrimeNumbers3(100000); Console.WriteLine("Primes 3: " + w.ElapsedMilliseconds.ToString()); w.Stop(); w.Start(); for (int i = 1; i <= 100000; i++) { int mod = i % 2; } w.Stop(); Console.WriteLine("Primes 4: " + w.ElapsedMilliseconds.ToString()); }
public static void TestProgram() { var sw = new Stopwatch(); sw.Start(); Console.WriteLine("Fi(30) = {0} - slow", CalculateNthFi(30)); sw.Stop(); Console.WriteLine("Calculated in {0}", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); Console.WriteLine("Fi(30) = {0} - fast", CalculateNthFi2(30)); sw.Stop(); Console.WriteLine("Calculated in {0}", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); Console.WriteLine("Fi(30) = {0} - fast2", CalculateNthFi3(30, 0, 1, 1)); sw.Stop(); Console.WriteLine("Calculated in {0}", sw.ElapsedMilliseconds); Console.WriteLine(""); }
public void CodeGeneration_PerformanceTest() { var sw = new Stopwatch(); sw.Start(); var func = CodeGeneration.GetVectorMultiplyFunction<int>(); sw.Stop(); Console.WriteLine("Generating & Compiling method time : {0} ms ({1} ticks)", sw.ElapsedMilliseconds, sw.ElapsedTicks); const int TrialCount = 10000; var first = Enumerable.Range(0, 100).ToArray(); var second = Enumerable.Range(0, 100).ToArray(); // Cold start for JIT-compiling func(first, second); CodeGeneration.MultuplyVectors(first, second); sw.Reset(); sw.Start(); for (int i = 0; i < TrialCount; i++) func(first, second); sw.Stop(); Console.WriteLine("Generated code : {0} ms ({1} ticks)", sw.ElapsedMilliseconds, sw.ElapsedTicks); sw.Reset(); sw.Start(); for (int i = 0; i < TrialCount; i++) CodeGeneration.MultuplyVectors(first, second); sw.Stop(); Console.WriteLine("Static code : {0} ms ({1} ticks)", sw.ElapsedMilliseconds, sw.ElapsedTicks); }
private void btnInterpretate_Click(object sender, EventArgs e) { try { Stopwatch timer = new Stopwatch(); RegularExpression r; timer.Reset(); timer.Start(); r = new RegularExpression(txtRegEx.Text); timer.Stop(); ReportResult("Parsing '" + txtRegEx.Text + "'", "SUCCESS", r.IsCompiled, timer); timer.Reset(); timer.Start(); bool result = r.IsMatch(txtInput.Text); timer.Stop(); ReportResult("Matching '" + txtInput.Text + "'", result.ToString(), r.IsCompiled, timer); ReportData("Original Expression:\t" + r.OriginalExpression + "\r\nInfix Expression:\t" + r.FormattedExpression + "\r\nPostfix string:\t" + r.PostfixExpression + "\r\n\r\nNon Deterministic Automata has\t\t" + r.NDStateCount + " states.\r\nDeterministic Automata has\t\t" + r.DStateCount + " states.\r\nOptimized Deterministic Automata has\t" + r.OptimizedDStateCount + " states."); automataViewer1.Initialize(r); } catch (RegularExpressionParser.RegularExpressionParserException exc) { ReportError("PARSER ERROR", exc.ToString()); } catch (Exception exc) { ReportError("EXCEPTION", exc.ToString()); } }
public void Test_perf_of_query_without_index() { OdbFactory.Delete("index1perf.ndb"); using (var odb = OdbFactory.Open("index1perf.ndb")) { for (var i = 0; i < 5000; i++) { var player = new Player("Player" + i, DateTime.Now, new Sport("Sport" + i)); odb.Store(player); } } var stopwatch = new Stopwatch(); stopwatch.Start(); using (var odb = OdbFactory.OpenLast()) { var query = odb.Query<Player>(); query.Descend("Name").Constrain((object) "Player20").Equal(); var count = query.Execute<Player>().Count; Assert.That(count, Is.EqualTo(1)); } stopwatch.Stop(); Console.WriteLine("Elapsed {0} ms", stopwatch.ElapsedMilliseconds); stopwatch.Reset(); stopwatch.Start(); using (var odb = OdbFactory.OpenLast()) { var query = odb.Query<Player>(); query.Descend("Name").Constrain((object) "Player1234").Equal(); var count = query.Execute<Player>().Count; Assert.That(count, Is.EqualTo(1)); } stopwatch.Stop(); Console.WriteLine("Elapsed {0} ms", stopwatch.ElapsedMilliseconds); stopwatch.Reset(); stopwatch.Start(); using (var odb = OdbFactory.OpenLast()) { var query = odb.Query<Player>(); query.Descend("Name").Constrain((object) "Player4444").Equal(); var count = query.Execute<Player>().Count; Assert.That(count, Is.EqualTo(1)); } stopwatch.Stop(); Console.WriteLine("Elapsed {0} ms", stopwatch.ElapsedMilliseconds); stopwatch.Reset(); stopwatch.Start(); using (var odb = OdbFactory.OpenLast()) { var query = odb.Query<Player>(); query.Descend("Name").Constrain((object) "Player3211").Equal(); var count = query.Execute<Player>().Count; Assert.That(count, Is.EqualTo(1)); } stopwatch.Stop(); Console.WriteLine("Elapsed {0} ms", stopwatch.ElapsedMilliseconds); }
public void TestTryConvertPerformance() { double NUM_ITERATIONS = Math.Pow(10, 6); Stopwatch watch = new Stopwatch(); Trace.WriteLine("Converting ints"); watch.Start(); for (double i = 0; i < NUM_ITERATIONS; i++) { int test = TypeUtils.TryConvert<int>("1234"); } watch.Stop(); Trace.WriteLine("Elapsed Time: " + watch.Elapsed.TotalSeconds); watch.Reset(); Trace.WriteLine("Converting int?s"); watch.Start(); for (double i = 0; i < NUM_ITERATIONS; i++) { int? test = TypeUtils.TryConvert<int?>("1234"); } watch.Stop(); Trace.WriteLine("Elapsed Time: " + watch.Elapsed.TotalSeconds); watch.Reset(); }
public void Check_performance() { var sw = new Stopwatch(); int numIterations = 1000000; sw.Start(); for (int i = 0; i < numIterations; i++) { i.IsMessage(); } sw.Stop(); Console.WriteLine("Not cached: " + sw.ElapsedMilliseconds); sw.Reset(); var hashTable = new Dictionary<Type, bool>(); sw.Start(); for (int i = 0; i < numIterations; i++) { hashTable[i.GetType()] = i.IsMessage(); } sw.Stop(); Console.WriteLine("Set dictionary: " + sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); for (int i = 0; i < numIterations; i++) { var r = hashTable[i.GetType()]; } sw.Stop(); Console.WriteLine("Get dictionary: " + sw.ElapsedMilliseconds); }
static void Main(string[] args) { InputLoader loader = new InputLoader(); loader.LoadFile("digits.csv"); Stopwatch sw = new Stopwatch(); var heursiticDetection = new HeuristicDetection(10, 5, quantity:50, numberOfPoints:500); var hypothesis = new CurrentHypothesis(); foreach (var input in loader.AllElements()) { ///For every new input we extract n points of interest ///And create a feature vector which characterizes the spatial relationship between these features ///For every heuristic we get a dictionary of points of interest DetectedPoints v = heursiticDetection.getFeatureVector(input.Item1); ///Compare this feature vector agaist each of the other feature vectors we know about sw.Reset(); sw.Start(); TestResult r = hypothesis.Predict(v); Debug.Print("Prediction: " + sw.Elapsed.Milliseconds.ToString()); var best= r.BestResult(); if(best != null && best.Item2 != 0){ LogProgress(best.Item1, input.Item2); } sw.Reset(); sw.Start(); hypothesis.Train(v, input.Item2, r); Debug.Print("Training: " + sw.Elapsed.Milliseconds.ToString()); //heursiticDetection.pointsOfInterest.Add(HeuristicDetection.Generate(10, 5, 10)); } }
static void Main(string[] args) { var sw = new Stopwatch(); Console.WriteLine("The difference between the sum of the squares of the first one hundred natural numbers and the square of the sum"); sw.Start(); var num1 = BruteForceWay(100); sw.Stop(); Console.WriteLine(string.Format("Plain loop addition brute force way(Linq aggregate)(tick:{0}): {1}", sw.ElapsedTicks, num1)); sw.Reset(); Console.WriteLine("The difference between the sum of the squares of the first one hundred natural numbers and the square of the sum"); sw.Start(); var num3 = BruteForceWay2(100); sw.Stop(); Console.WriteLine(string.Format("Plain loop addition brute force way(for loop)(tick:{0}): {1}", sw.ElapsedTicks, num3)); sw.Reset(); Console.WriteLine("The difference between the sum of the squares of the first one hundred natural numbers and the square of the sum"); sw.Start(); var num2 = ArithmeticWay(100); sw.Stop(); Console.WriteLine(string.Format("Smart Arithmetic Way(tick:{0}): {1}", sw.ElapsedTicks, num2)); Console.WriteLine("Press any key to exit"); Console.ReadKey(); }
public static void run(Action testMethod, int rounds){ Stopwatch stopwatch = new Stopwatch(); stopwatch.Reset(); stopwatch.Start(); while (stopwatch.ElapsedMilliseconds < 1200) // A Warmup of 1000-1500 mS // stabilizes the CPU cache and pipeline. { testMethod(); // Warmup clearMemory (); } stopwatch.Stop(); long totalmem; Console.WriteLine ("Round;Runtime ms;Memory KB"); for (int repeat = 0; repeat < rounds; ++repeat) { stopwatch.Reset(); stopwatch.Start(); testMethod(); stopwatch.Stop(); totalmem = getUsedMemoryKB (); clearMemory (); Console.WriteLine((1+repeat)+";"+stopwatch.ElapsedMilliseconds + ";" +totalmem); } }
public void SetAll() { writeCount = 0; writeTime = 0; Stopwatch watch = new Stopwatch(); watch.Reset(); watch.Start(); foreach (var kv in initialData) if (stopFlag == false) { storageToWrite.Set(kv.Key, kv.Value, false); writeCount += 1; } else break; stopFlag = true; watch.Stop(); writeTime += (int)watch.ElapsedMilliseconds; watch.Reset(); watch.Start(); storageToWrite._btreeDb.Sync(); watch.Stop(); syncTime+= (int)watch.ElapsedMilliseconds; writeTime += (int)watch.ElapsedMilliseconds; }
static void Main(string[] args) { string data = File.ReadAllText(@"....."); Stopwatch watch = new Stopwatch(); for (int i = 0; i < 20; i++) { watch.Start(); Newtonsoft.Json.Linq.JObject jObj = Newtonsoft.Json.Linq.JObject.Parse(data); watch.Stop(); Console.WriteLine(watch.Elapsed); watch.Reset(); } Console.WriteLine(" "); GC.Collect(); for (int i = 0; i < 20; i++) { watch.Start(); JParser parser = new JParser(); JToken token = parser.Parse(data); watch.Stop(); Console.WriteLine(watch.Elapsed); watch.Reset(); } Console.WriteLine(" "); }
public static string Run(string out_dir) { var sb = new StringBuilder(); // Time creation of serializer var sw = new Stopwatch(); var serializer = new Serializer(); sb.AppendLine("Serializer init took " + sw.Elapsed); var data = SubClass.Sample(); // Time serializing prefs string out_file = Path.Combine(out_dir, "data.bin"); sw.Reset(); using (var stream = File.Create(out_file)) { serializer.Serialize(stream, data); } sb.AppendLine("Serialization took " + sw.Elapsed); // Time de-serializing prefs sw.Reset(); using (var stream = File.OpenRead(out_file)) { data = (SubClass)serializer.Deserialize(stream, null, typeof(SubClass)); } sb.AppendLine("De-serialization took " + sw.Elapsed); sb.AppendLine("Date_Saved: " + data.Date_Saved); sb.AppendLine("Field1: " + data.Field1); sb.AppendLine("Field2: " + data.Field2); return sb.ToString(); }
public static void CompareParsers() { var sw = new Stopwatch(); StreamResourceInfo xmlStream1 = Application.GetResourceStream(new Uri("/WP.Common;component/Data/books3.xml", UriKind.Relative)); sw.Start(); var obj3 = XmlParser.ParseBooksUsingXmlReader(xmlStream1.Stream); sw.Stop(); Debug.WriteLine(string.Format("Parsing using XmlReader: {0} ms", sw.ElapsedMilliseconds)); xmlStream1.Stream.Close(); sw.Reset(); Thread.Sleep(1000); StreamResourceInfo xmlStream2 = Application.GetResourceStream(new Uri("/WP.Common;component/Data/books2.xml", UriKind.Relative)); sw.Start(); var obj1 = XmlParser.ParseBooksUsingLinqToXml(xmlStream2.Stream); sw.Stop(); Debug.WriteLine(string.Format("Parsing using LinqToXml: {0} ms", sw.ElapsedMilliseconds)); xmlStream2.Stream.Close(); sw.Reset(); Thread.Sleep(1000); StreamResourceInfo xmlStream3 = Application.GetResourceStream(new Uri("/WP.Common;component/Data/books.xml", UriKind.Relative)); sw.Start(); DateTime dt2 = DateTime.Now; var obj2 = XmlParser.ParseBooksUsingXmlDeserialization(xmlStream3.Stream); sw.Stop(); Debug.WriteLine(string.Format("Parsing using Xml Deserialization: {0} ms", sw.ElapsedMilliseconds)); xmlStream3.Stream.Close(); sw.Reset(); Thread.Sleep(1000); }
static void Main(string[] args) { List<Tuple<string, int, long>> results = new List<Tuple<string, int, long>>(); Stopwatch stopWatch = new Stopwatch(); DataTable dataTable; for (int testCount = 10; testCount <= 1000000; testCount *= 10) { GC.Collect(); dataTable = CreateTestTable(testCount); stopWatch.Reset(); stopWatch.Start(); RunManualAssignmentTest(dataTable); stopWatch.Stop(); results.Add(new Tuple<string, int, long>("Manual Assignment", testCount, stopWatch.ElapsedMilliseconds)); dataTable.Dispose(); GC.Collect(); dataTable = CreateTestTable(testCount); stopWatch.Reset(); stopWatch.Start(); RunStaticAssignmentTest(dataTable); stopWatch.Stop(); results.Add(new Tuple<string, int, long>("Static RuntimeMapper", testCount, stopWatch.ElapsedMilliseconds)); dataTable.Dispose(); GC.Collect(); dataTable = CreateTestTable(testCount); stopWatch.Reset(); stopWatch.Start(); RunPreCachedAssignmentTest(dataTable); stopWatch.Stop(); results.Add(new Tuple<string, int, long>("Cached RuntimeMapper", testCount, stopWatch.ElapsedMilliseconds)); dataTable.Dispose(); GC.Collect(); } var csvFile = @"performanceTest_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".csv"; System.IO.File.AppendAllText(csvFile, "Test,Count,Time (ms)\n"); foreach (var result in results) { Console.WriteLine(result.Item1 + " (" + result.Item2 + "): " + result.Item3.ToString() + "ms"); Console.WriteLine("--------------------"); System.IO.File.AppendAllText(csvFile, result.Item1 + "," + result.Item2.ToString() + "," + result.Item3.ToString() + "\n"); } Console.ReadKey(); }
static void Main(string[] args) { Random r = new Random(); //generate data set string[] data0 = new string[N], data1 = new string[N]; char[] chars = new char[Length]; for (int i = 0; i < N; ++i) { for (int j = 0; j < Length; ++j) chars[j] = (char)(FirstChar + r.Next(AlphabetSize)); data0[i] = data1[i] = new string(chars); } Stopwatch time = new Stopwatch(); //test QSort time.Start(); Array.Sort(data0); Console.WriteLine("QSort'ed in "+time.ElapsedMilliseconds+" ms"); time.Reset(); //test RadixSort time.Start(); RadixSort(data1); Console.WriteLine("RadixSort'ed in " + time.ElapsedMilliseconds + " ms"); time.Reset(); if (Console.ReadKey().Key != ConsoleKey.Spacebar) return; Console.WriteLine("Press spacebar to print the sorted data or any other key to quit"); foreach (string s in data1) Console.WriteLine(s); Console.ReadKey(); }
private void RunTests(Harness harness) { Clients.All.showmessage("Starting " + harness.Name + " tests..."); var sw = new Stopwatch(); sw.Start(); for (var i = 0; i < OPERATIONS; i++) { var data = i.ToString(); harness.Create(data); } sw.Stop(); Clients.All.showmessage("Put " + OPERATIONS + " values in " + sw.ElapsedMilliseconds + "ms."); sw.Reset(); sw.Start(); for (var i = 0; i < OPERATIONS; i++) { var data = i.ToString(); harness.Read(data); } sw.Stop(); Clients.All.showmessage("Read " + OPERATIONS + " values in " + sw.ElapsedMilliseconds + "ms."); sw.Reset(); sw.Start(); for (var i = 0; i < OPERATIONS; i++) { var data = i.ToString(); harness.Delete(data); } sw.Stop(); Clients.All.showmessage("Deleted " + OPERATIONS + " values in " + sw.ElapsedMilliseconds + "ms."); Clients.All.showmessage("Completed " + harness.Name + " tests..."); }
// Update is called once per frame void Update() { if(Input.GetKeyDown(KeyCode.Space)) { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Reset(); // Single call test watch.Start (); SingleCall (); watch.Stop (); long elapsedSingle = watch.ElapsedTicks; Debug.Log ("Single call: " + elapsedSingle + " ticks"); watch.Reset(); // Multicall test watch.Start (); for(int t = 0; t < Iterations; ++t) { MultiCall(); } watch.Stop (); long elapsedMulti = watch.ElapsedTicks; Debug.Log ("Multi call: " + elapsedMulti + " ticks"); Debug.Log ("Ratio (Multi/Single): " + elapsedMulti / (double)elapsedSingle); } }
public void AddLots() { var expression = "X = (((A + B) * (A + B)) * ((A + B) * (A + B))) + (((A + B) * (A + B)) * ((A + B) * (A + B)))"; const int _size = 1000000; _data = new Dictionary<string, IEnumerable<KeyValuePair<string, Atom>>> { {"A", Enumerable.Range(0, _size).Select(i => new KeyValuePair<string,Atom>("", i + .0))}, {"B", Enumerable.Range(_size, _size).Select(i => new KeyValuePair<string,Atom>("", i + .0))}, }; var watch = new Stopwatch(); watch.Reset(); Console.WriteLine("Start sequential..."); watch.Start(); var result2 = ComputeSequential(expression, _size)["X"](new[]{new KeyValuePair<string, Atom>[0]}).Select(item => item.Value).ToArray(); watch.Stop(); Console.WriteLine("Sequential elapsed:{0}", watch.Elapsed); watch.Reset(); Console.WriteLine("Start parallel..."); watch.Start(); var result = ComputeParallel(expression, _size)["X"](new[]{new KeyValuePair<string, Atom>[0]}).Select(item => item.Value).ToArray(); watch.Stop(); Console.WriteLine("Parallel elapsed:{0}", watch.Elapsed); CollectionAssert.AreEqual(result, result2); }
void Start() { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Reset(); sw.Start(); for (int i = 0; i < 100000; i++) { GameObject a = Instantiate(Resources.Load<GameObject>("A")); a.AddComponent<TestA>(); } sw.Stop(); print("1:"+sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); for (int i = 0; i < 100000; i++) { GameObject a = Instantiate(Resources.Load<GameObject>("B")); } sw.Stop(); print("2:" + sw.ElapsedMilliseconds); }
private static void DoubleOperations() { Stopwatch sw = new Stopwatch(); sw.Start(); double result = 0; for (int i = 0; i < count; i++) { result = Math.Sqrt(7); } Console.WriteLine("Math.Sqrt(): {0}", sw.Elapsed); sw.Reset(); sw.Start(); for (int i = 0; i < count; i++) { result = Math.Log(7); } Console.WriteLine("Math.Log(): {0}", sw.Elapsed); sw.Reset(); sw.Start(); for (int i = 0; i < count; i++) { result = Math.Sin(7); } Console.WriteLine("Math.Sin(): {0}", sw.Elapsed); }
private static TimeSpan[] RunFirstQueryMeasurements(AdsEntities ctx, Stopwatch stopwatch) { ctx.Database.SqlQuery<Ad>("CHECKPOINT; DBCC DROPCLEANBUFFERS;"); var firstQueryRunDurations = new TimeSpan[10]; for (int index = 0; index < 10; index++) { stopwatch.Reset(); stopwatch.Start(); var adsQueryStupid = ctx.Ads.ToList() .Where(a => a.AdStatus.Status.Equals("Published")) .Select(a => new { a.Title, a.Category, a.Town, a.Date }) .ToList() .OrderBy(a => a.Date); firstQueryRunDurations[index] = stopwatch.Elapsed; } stopwatch.Reset(); return firstQueryRunDurations; }
static void Main() { Stopwatch crono = new Stopwatch(); float tMono, tForEach, tFor; crono.Start(); string[] ficheros = Directory.GetFiles(@"..\..\..\pics", "*.jpg"); string nuevoDirectorio = @"..\..\..\pics\rotadas"; Directory.CreateDirectory(nuevoDirectorio); crono.Start(); VersionMonoHilo(ficheros, nuevoDirectorio); crono.Stop(); tMono = crono.ElapsedMilliseconds; Console.WriteLine("Ejecutado monohilo en {0:N} milisegundos.\n", tMono); crono.Reset(); crono.Start(); VersionForEach(ficheros, nuevoDirectorio); crono.Stop(); tForEach = crono.ElapsedMilliseconds; Console.WriteLine("Ejecutado ForEach en {0:N} milisegundos.\n", tForEach); crono.Reset(); crono.Start(); VersionFor(ficheros, nuevoDirectorio); crono.Stop(); tFor = crono.ElapsedMilliseconds; Console.WriteLine("Ejecutado For en {0:N} milisegundos.\n", tFor); float beneficio = 100 - ((tForEach / tMono) * 100); Console.WriteLine("Beneficio de rendimiento Mono vs ForEach {0:N} %", beneficio); beneficio = 100 - ((tFor / tMono) * 100); Console.WriteLine("Beneficio de rendimiento Mono vs For {0:N} %\n", beneficio); }
public static void Main() { // Test sorting array of ints int[] testIntArr = SortingMethods.GenerateIntArr(); SortingMethods.InsertionSort(testIntArr); Stopwatch sw = new Stopwatch(); sw.Start(); testIntArr = SortingMethods.GenerateIntArr(); SortingMethods.QuickSort(testIntArr, 0, testIntArr.Length - 1); sw.Stop(); long algorithmNeededTime = sw.ElapsedMilliseconds; sw.Reset(); Console.WriteLine( "Quick sort algorithm with integers needed {0} milliseconds.", algorithmNeededTime); testIntArr = SortingMethods.GenerateIntArr(); SortingMethods.SelectionSort(testIntArr); Console.WriteLine(); // Test sorting array of double double[] testDoubleArr = SortingMethods.GenerateDoubleArr(); SortingMethods.InsertionSort(testDoubleArr); sw.Start(); testDoubleArr = SortingMethods.GenerateDoubleArr(); SortingMethods.QuickSort(testDoubleArr, 0, testDoubleArr.Length - 1); sw.Stop(); algorithmNeededTime = sw.ElapsedMilliseconds; sw.Reset(); Console.WriteLine( "Quick sort algorithm with double needed {0} milliseconds.", algorithmNeededTime); testDoubleArr = SortingMethods.GenerateDoubleArr(); SortingMethods.SelectionSort(testDoubleArr); Console.WriteLine(); // Test sorting array of strings string[] testStringArr = SortingMethods.GenerateStringArr(); SortingMethods.InsertionSort(testStringArr); sw.Start(); testStringArr = SortingMethods.GenerateStringArr(); SortingMethods.QuickSort(testStringArr, 0, testStringArr.Length - 1); sw.Stop(); algorithmNeededTime = sw.ElapsedMilliseconds; sw.Reset(); Console.WriteLine( "Quick sort algorithm with strings needed {0} milliseconds.", algorithmNeededTime); testStringArr = SortingMethods.GenerateStringArr(); SortingMethods.SelectionSort(testStringArr); Console.WriteLine(); Console.WriteLine("My experiment show that Quick sort is the fastest algorithm."); }
public static void Test() { Person.Exam[] exam1 = new Person.Exam[10]; Person.Exam[,] exam2 = new Person.Exam[5,2]; Person.Exam[][] exam3 = new Person.Exam[3][]; for (int i = 0; i < 10; i++) { exam1[i] = new Person.Exam("Math", 4, DateTime.Parse("2013-12-12")); } for (int i = 0; i < 5; i++) { for (int j = 0; j < 2; j++) { exam2[i,j] = new Person.Exam("Math", 4, DateTime.Parse("2013-12-12")); } } exam3[0] = new Person.Exam[2] { new Person.Exam("Math", 4, DateTime.Parse("2013-12-12")), new Person.Exam("Math", 4, DateTime.Parse("2013-12-12")) }; exam3[1] = new Person.Exam[3] { new Person.Exam("Math", 4, DateTime.Parse("2013-12-12")), new Person.Exam("Math", 4, DateTime.Parse("2013-12-12")), new Person.Exam("Math", 4, DateTime.Parse("2013-12-12")) }; exam3[2] = new Person.Exam[5] { new Person.Exam("Math", 4, DateTime.Parse("2013-12-12")), new Person.Exam("Math", 4, DateTime.Parse("2013-12-12")), new Person.Exam("Math", 4, DateTime.Parse("2013-12-12")), new Person.Exam("Math", 4, DateTime.Parse("2013-12-12")), new Person.Exam("Math", 4, DateTime.Parse("2013-12-12")) }; Person.Exam testExam; Stopwatch sWatch = new Stopwatch(); sWatch.Start(); foreach (Person.Exam item in exam1) { testExam = (Person.Exam)item.DeepCopy(); } sWatch.Stop(); Console.WriteLine(sWatch.Elapsed.ToString()); Console.WriteLine(); sWatch.Reset(); sWatch.Start(); foreach (Person.Exam item in exam2) { testExam = (Person.Exam)item.DeepCopy(); } sWatch.Stop(); Console.WriteLine(sWatch.Elapsed.ToString()); Console.WriteLine(); sWatch.Reset(); sWatch.Start(); foreach (Person.Exam[] itemList in exam3) { foreach (Person.Exam item in itemList) { testExam = (Person.Exam)item.DeepCopy(); } } sWatch.Stop(); Console.WriteLine(sWatch.Elapsed.ToString()); Console.WriteLine(); }
static void Main(string[] args) { using(var file=new StreamReader(args[0])) { RedisServer redis = new RedisServer(); ModelProducer producer = new ModelProducer(); Stopwatch s_watch = new Stopwatch(); ReputationBase db=new ReputationBase(ConfigurationSettings.AppSettings["MainBase"]); int count = 0; string stat = ""; while(!file.EndOfStream) { s_watch.Start(); string line = file.ReadLine(); long Id=Convert.ToInt64(line); s_watch.Stop(); stat += s_watch.ElapsedTicks + "/"; s_watch.Reset(); s_watch.Start(); var company = db.GetCompany(Id);//получение общей информации о компании s_watch.Stop(); stat += s_watch.ElapsedTicks + "/"; s_watch.Reset(); if (company == null) continue; s_watch.Start(); var relations = db.GetRelations(Id); s_watch.Stop(); stat += s_watch.ElapsedTicks + "/"; s_watch.Reset(); s_watch.Start(); redis.SetCompany(company); redis.SetRelations(Id, relations); s_watch.Stop(); stat += s_watch.ElapsedTicks + "/"; s_watch.Reset(); count++; if (count % 100 == 0) Console.WriteLine(count+", statistics: "+stat); stat = ""; } } }
/// <summary> /// 计时器开始 /// </summary> /// <returns></returns> public static Diagnostics.Stopwatch TimerStart() { var watch = new Diagnostics.Stopwatch(); watch.Reset(); watch.Start(); return(watch); }
public static int Main() { if (!Vector.IsHardwareAccelerated) { Console.WriteLine("Not hardware accelerated!"); } else { Console.WriteLine("Vector<double>.Length: " + Vector <double> .Count); } int nx = 10001; #if DEBUG int nt = 10; #else int nt = 10000; #endif double dx = 2.0 * Math.PI / (nx - 1.0); double nu = 0.07; double dt = dx * nu; double[] x = linspace(0.0, 2.0 * Math.PI, nx); double[] initial = GetAnalytical(x, 0.0, nu); // Warmup GetCalculated0(1, nx, dx, dt, nu, initial); GetCalculated1(1, nx, dx, dt, nu, initial); GetCalculated2(1, nx, dx, dt, nu, initial); GetCalculated3(1, nx, dx, dt, nu, initial); double[][] results = new double[4][]; var stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Start(); results[0] = GetCalculated0(nt, nx, dx, dt, nu, initial); stopwatch.Stop(); Console.WriteLine("Baseline: " + stopwatch.ElapsedMilliseconds); stopwatch.Reset(); stopwatch.Start(); results[1] = GetCalculated1(nt, nx, dx, dt, nu, initial); stopwatch.Stop(); Console.WriteLine("Reduce copy: " + stopwatch.ElapsedMilliseconds); stopwatch.Reset(); stopwatch.Start(); results[2] = GetCalculated2(nt, nx, dx, dt, nu, initial); stopwatch.Stop(); Console.WriteLine("CSE of Math.Pow: " + stopwatch.ElapsedMilliseconds); stopwatch.Reset(); stopwatch.Start(); results[3] = GetCalculated3(nt, nx, dx, dt, nu, initial); stopwatch.Stop(); Console.WriteLine("SIMD: " + stopwatch.ElapsedMilliseconds); stopwatch.Reset(); for (int i = 0; i < x.Length; i += 33) { double expected = results[0][i]; for (int j = 1; j < results.Length; j++) { bool valid = Math.Abs(expected - results[j][i]) < 1e-4; if (!valid) { Console.WriteLine("Failed to validate"); return(-1); } } } return(100); }
public IEnumerator FinalizeTextures(System.Diagnostics.Stopwatch stopWatch) { if (coordList.Count == 0) // There's nothing that uses this. { yield break; } int scaleFactor = 1; if (tileWidth * 4 <= GameSettings.Instance.rendering.maxTextureSize && tileHeight * 4 <= GameSettings.Instance.rendering.maxTextureSize) { scaleFactor = 4; } else if (tileWidth * 3 <= GameSettings.Instance.rendering.maxTextureSize && tileHeight * 3 <= GameSettings.Instance.rendering.maxTextureSize) { scaleFactor = 3; } else if (tileWidth * 2 <= GameSettings.Instance.rendering.maxTextureSize && tileHeight * 2 <= GameSettings.Instance.rendering.maxTextureSize) { scaleFactor = 2; } tileArray = new Texture2DArray(Mathf.ClosestPowerOfTwo(tileWidth * scaleFactor), Mathf.ClosestPowerOfTwo(tileHeight * scaleFactor), coordList.Count, TextureFormat.ARGB32, true); normalArray = new Texture2DArray(Mathf.ClosestPowerOfTwo(tileWidth * scaleFactor), Mathf.ClosestPowerOfTwo(tileHeight * scaleFactor), coordList.Count, TextureFormat.ARGB32, true, true); for (int i = 0; i < coordList.Count; i++) { var coord = coordList[i]; var tileSource = originalPage.GetPixels(coord.x * tileWidth, (pageHeight - coord.y - 1) * tileHeight, tileWidth, tileHeight); var tileSource32 = new Color32[tileSource.Length]; for (int j = 0; j < tileSource.Length; j++) { tileSource32[j] = tileSource[j]; } var tileDest32 = new Color32[tileWidth * scaleFactor * tileHeight * scaleFactor]; switch (scaleFactor) { case 4: HqxSharp.Scale4(tileSource32, tileDest32, tileWidth, tileHeight); break; case 3: HqxSharp.Scale3(tileSource32, tileDest32, tileWidth, tileHeight); break; case 2: HqxSharp.Scale2(tileSource32, tileDest32, tileWidth, tileHeight); break; default: tileDest32 = tileSource32; break; } Texture2D texture = new Texture2D(tileWidth * scaleFactor, tileHeight * scaleFactor, TextureFormat.ARGB32, false); texture.SetPixels32(tileDest32); TextureScale.Bilinear(texture, Mathf.ClosestPowerOfTwo(tileWidth * scaleFactor), Mathf.ClosestPowerOfTwo(tileHeight * scaleFactor)); tileArray.SetPixels(texture.GetPixels(), i); normalArray.SetPixels(TextureTools.Bevel(texture.GetPixels(), texture.width, texture.height), i); if (stopWatch.ElapsedMilliseconds > 100) { yield return(null); stopWatch.Reset(); stopWatch.Start(); } } tileArray.Apply(); normalArray.Apply(); }
void Update() { switch (state_) { case State.CSharp: { System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); stopwatch_.Reset(); stopwatch_.Start(); for (int i = 0; i < NumSamples; ++i) { results_[i] = GetMD5Hash(md5, samples_[i]); } stopwatch_.Stop(); md5.Clear(); Debug.LogFormat("charp:{0} samples {1} sec", NumSamples, stopwatch_.Elapsed.TotalSeconds); state_ = State.xxHash; } break; case State.xxHash: { stopwatch_.Reset(); stopwatch_.Start(); //string str = "Nobody inspects the spammish repetition"; //string hashStr = LUtil.xxHash.GetHash(System.Text.Encoding.ASCII.GetBytes(str)); //Debug.Log(hashStr); for (int i = 0; i < NumSamples; ++i) { results_[i] = LUtil.xxHash.GetHash(samples_[i]); } stopwatch_.Stop(); Debug.LogFormat("xxHash:{0} samples {1} sec", NumSamples, stopwatch_.Elapsed.TotalSeconds); state_ = State.MurmurHash; } break; case State.MurmurHash: { //string str = "The quick brown fox jumps over the lazy dog"; //string hashStr = LUtil.MurmurHash.GetHash(System.Text.Encoding.ASCII.GetBytes(str)); //Debug.Log(hashStr); stopwatch_.Reset(); stopwatch_.Start(); for (int i = 0; i < NumSamples; ++i) { results_[i] = LUtil.MurmurHash.GetHash(samples_[i]); } stopwatch_.Stop(); Debug.LogFormat("MurmurHash:{0} samples {1} sec", NumSamples, stopwatch_.Elapsed.TotalSeconds); state_ = State.None; } break; case State.None: System.GC.Collect(); if (count_ < 10) { ++count_; state_ = State.CSharp; } break; } }
private void downloadFile(Int32 fileNr) { m_currentFileSize = 0; fireEventFromBgw(Event.FileDownloadAttempting); FileInfo file = this.Files[fileNr]; Int64 size = 0; Byte[] readBytes = new Byte[this.PackageSize]; Int32 currentPackageSize; System.Diagnostics.Stopwatch speedTimer = new System.Diagnostics.Stopwatch(); Int32 readings = 0; Exception exc = null; FileStream writer = new FileStream(this.LocalDirectory + System.IO.Path.DirectorySeparatorChar + file.Name, System.IO.FileMode.Create); HttpWebRequest webReq; HttpWebResponse webResp = null; try { webReq = (HttpWebRequest)System.Net.WebRequest.Create(this.Files[fileNr].Path); webReq.Proxy = new WebProxy(System.Net.WebRequest.GetSystemWebProxy().GetProxy(new Uri("http://dwsim.inforside.com.br"))); webReq.Proxy.Credentials = CredentialCache.DefaultCredentials; webResp = (HttpWebResponse)webReq.GetResponse(); size = webResp.ContentLength; } catch (Exception ex) { exc = ex; } m_currentFileSize = size; fireEventFromBgw(Event.FileDownloadStarted); if (exc != null) { bgwDownloader.ReportProgress((Int32)InvokeType.FileDownloadFailedRaiser, exc); } else { m_currentFileProgress = 0; while (m_currentFileProgress < size && !bgwDownloader.CancellationPending) { while (this.IsPaused) { System.Threading.Thread.Sleep(100); } speedTimer.Start(); currentPackageSize = webResp.GetResponseStream().Read(readBytes, 0, this.PackageSize); m_currentFileProgress += currentPackageSize; m_totalProgress += currentPackageSize; fireEventFromBgw(Event.ProgressChanged); writer.Write(readBytes, 0, currentPackageSize); readings += 1; if (readings >= this.StopWatchCyclesAmount) { m_currentSpeed = (Int32)(this.PackageSize * StopWatchCyclesAmount * 1000 / (speedTimer.ElapsedMilliseconds + 1)); speedTimer.Reset(); readings = 0; } } speedTimer.Stop(); writer.Close(); webResp.Close(); if (!bgwDownloader.CancellationPending) { fireEventFromBgw(Event.FileDownloadSucceeded); } } fireEventFromBgw(Event.FileDownloadStopped); }
public void StartSW(string name = "") { Debug.Log("开始========>> stopwatch: " + name); _stopWatch.Reset(); _stopWatch.Start(); }
IEnumerator total() //트레이닝용 자극 0.5 + 0.5 + 0.5 + 0.5 + 3 = 5초 { yield return(new WaitForSeconds(0.5F)); sw.Start(); now = sw.ElapsedMilliseconds; prints = now - before; // 지연시간 측정 before = now; Debug.Log("start :" + prints); network.SendMessage("Send", prints + "#x#"); rend[repeatindex[count] - 1].sharedMaterial = materials[1]; //정답 표시 answer = Random.Range(1, 7); yield return(new WaitForSeconds(0.5F)); switch (answer) { case 1: if (training) { network.SendMessage("Send", prints + "#a#"); } break; case 2: if (training) { network.SendMessage("Send", prints + "#b#"); } break; case 3: if (training) { network.SendMessage("Send", prints + "#c#"); } break; case 4: if (training) { network.SendMessage("Send", prints + "#d#"); } break; case 5: if (training) { network.SendMessage("Send", prints + "#e#"); } break; case 6: if (training) { network.SendMessage("Send", prints + "#f#"); } break; } // abcdef = 트리거 123456 // 각 신호는 #으로 구별 //prints = 홀로렌즈에서 각 프레임별 지속 시간. 이걸 기반으로 시간을 재조립 yield return(new WaitForSeconds(0.5F)); network.SendMessage("Send", prints + "#y#"); // 트리거 12 now = sw.ElapsedMilliseconds; prints = now - before; before = now; Debug.Log("ready :" + prints); rend[repeatindex[count] - 1].sharedMaterial = materials[0]; // 되돌리기 yield return(new WaitForSeconds(0.5F)); count = 0; for (int i = 0; i < repeatnumber * 6; i++) { count++; if (StaticClass.type == 1) { yield return(StartCoroutine(on())); // 깜빡임 } else { yield return(StartCoroutine(spinon())); // 회전 } } yield return(new WaitForSeconds(3F)); now = sw.ElapsedMilliseconds; prints = now - before; // 시간 측정 before = now; Debug.Log("end :" + prints); network.SendMessage("Send", prints + "#z#"); // 트리거 13 end = true; sw.Stop(); //스톱워치 정지 sw.Reset(); //스톱워치 리셋 now = 0; prints = 0; before = 0; }
// Start is called before the first frame update void Start() { testArray = new float[1000, 1000]; for (int i = 0; i < testArray.GetLength(0); i++) { for (int j = 0; j < testArray.GetLength(1); j++) { testArray[i, j] = Random.value * 100; } } // Flatten the array wow! array = testArray.Cast <float>().ToArray(); System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch(); timer.Start(); //TestSqrt(); timer.Stop(); Debug.Log(timer.ElapsedMilliseconds); int kernel = shader.FindKernel("test"); // Can be null! result = new RenderTexture(128, 128, 32); result.enableRandomWrite = true; result.Create(); shader.SetTexture(kernel, "Result", result); floats = new ComputeBuffer(array.Length, 4); shader.SetBuffer(kernel, "floats", floats); shader.SetInt("columnsize", testArray.GetLength(0)); timer.Reset(); timer.Start(); floats.SetData(array); // for (int i = 0; i < iterations; i++) { shader.Dispatch(kernel, 1000 / 32, 1000 / 32, 1); } // floats.GetData(array); timer.Stop(); Debug.Log(timer.ElapsedMilliseconds); // shader.SetVectorArray(kernel, ) }
public void ResetTimer() { stopwatch.Reset(); }
// Use this for initialization void Start() { InitGUI(); #if UNITY_4_6 || UNITY_4_7 Application.RegisterLogCallback(ShowTips); #else Application.logMessageReceived += ShowTips; #endif new LuaResLoader(); luaState = new LuaState(); luaState.Start(); LuaBinder.Bind(luaState); //For InjectByModule ////////////////////////////////////////////////////// luaState.BeginModule(null); BaseTestWrap.Register(luaState); ToLuaInjectionTestWrap.Register(luaState); luaState.EndModule(); ////////////////////////////////////////////////////// #if ENABLE_LUA_INJECTION #if UNITY_EDITOR if (UnityEditor.EditorPrefs.GetInt(Application.dataPath + "InjectStatus") == 1) { #else if (true) { #endif ///此处Require是示例专用,暖更新的lua代码都要放到LuaInjectionBus.lua中统一require luaState.Require("ToLuaInjectionTestInjector"); int counter = 0; bool state = true; ToLuaInjectionTest test = new ToLuaInjectionTest(true); test = new ToLuaInjectionTest(); StartCoroutine(test.TestCoroutine(0.3f)); test.TestOverload(1, state); test.TestOverload(1, ref state); Debug.Log("TestOverload ref result:" + state); test.TestOverload(state, 1); int refResult = test.TestRef(ref counter); Debug.Log(string.Format("TestRef return result:{0}; ref result:{1}", refResult, counter)); Debug.Log("Property Get Test:" + test.PropertyTest); test.PropertyTest = 2; Debug.Log("Property Set Test:" + test.PropertyTest); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); for (int i = 0; i < 10000000; ++i) { test.NoInject(true, 1); } sw.Stop(); long noInjectMethodCostTime = sw.ElapsedMilliseconds; sw.Reset(); sw.Start(); for (int i = 0; i < 10000000; ++i) { test.Inject(true, 1); } sw.Stop(); Debug.Log("time cost ratio:" + (double)sw.ElapsedMilliseconds / noInjectMethodCostTime); } else #endif { Debug.LogError("查看是否开启了宏ENABLE_LUA_INJECTION并执行了菜单命令——\"Lua=>Inject All\""); } } void InitGUI() { m_windowRect.x = 0; m_windowRect.y = 0; m_windowRect.width = Screen.width; m_windowRect.height = Screen.height; m_logFontSize = (int)(m_fontSize * Screen.width * Screen.height / (1280 * 720)); m_normalColor = Color.white; m_fontStyle = new GUIStyle(); m_fontStyle.normal.textColor = m_normalColor; m_fontStyle.fontSize = m_logFontSize; //设置窗口颜色 m_windowStyle = new GUIStyle(); Texture2D windowTexture = new Texture2D(1, 1); windowTexture.SetPixel(0, 0, Color.black); windowTexture.Apply(); m_windowStyle.normal.background = windowTexture; scaleThreshold = Screen.width / 1100.0f; } void OnApplicationQuit() { #if UNITY_5 || UNITY_2017_1_OR_NEWER Application.logMessageReceived -= ShowTips; #else Application.RegisterLogCallback(null); #endif luaState.Dispose(); luaState = null; } Vector2 MousePoisition { get { return(new Vector2(-Input.mousePosition.x, Input.mousePosition.y)); } }
//Main Thread //Called in separate process: Child of PlStream job public void VelocityThread2() { //internal variables float deltaTime = 0f; double currentTimestep = 0; //thread variables // int i = 0; Quaternion coil_orientation; if (threadGo) { stopwatch.Stop(); currentTimestep = stopwatch.Elapsed.TotalSeconds; stopwatch.Reset(); stopwatch.Start(); //deltaTime += (float)(currentTimestep); deltaTime = (float)currentTimestep; // lastTime = (float)currentTimestep; //Stopwatch reset if (deltaTime >= .001f) { /* * transfers plstream translated bit information to unity engine parameters */ //pol_position = plstream.positions[i] - prime_position; coil_orientation = clstream.currentHeadOrientation; //-calibrate_rotation; // Convert quaternion in coil coordinates to Unity coordinates // Coil is RHR: X forward, Y left, Z up // Unity is LHR: X right, Y up, Z forward /*currentRotation.w = coil_orientation[0]; * currentRotation.x = coil_orientation[2]; // Unity X = -coil Y * currentRotation.y = coil_orientation[3]; // Unity Y = coil Z * currentRotation.z = coil_orientation[1]; // Unity Z = coil X*/ currentRotation = new Quaternion(coil_orientation.y, -coil_orientation.z, coil_orientation.x, coil_orientation.w); //recalibrated rotation currentRotation = currentRotation * Quaternion.Inverse(referenceOrientation); angularVelocityRead.x = -clstream.currentHeadVelocity[1]; // Unity X = -coil Y angularVelocityRead.y = clstream.currentHeadVelocity[2]; // Unity Y = coil Z angularVelocityRead.z = clstream.currentHeadVelocity[0]; // Unity Z = coil X streamSample = clstream.simulinkSample; logger.Append(deltaTime.ToString() + "\t"); logger.Append(streamSample.ToString() + "\t"); logger.Append(currentRotation.w + "\t"); logger.Append(currentRotation.x + "\t"); logger.Append(currentRotation.y + "\t"); logger.Append(currentRotation.z + "\t"); logger.Append(angularVelocityRead.x + "\t"); logger.Append(angularVelocityRead.y + "\t"); logger.Append(angularVelocityRead.z + "\t "); logger.AppendLine(); time = deltaTime; deltaTime = 0; } } return; }
public void TestAddBug() { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); var tree = new RedBlackTree <TestNode>(); sw.Reset(); sw.Start(); var list1 = new List <TestNode>(); for (int i = 100000; i >= 0; --i) { list1.Add(new TestNode(i)); } for (int i = 100000; i >= 0; --i) { list1.Insert(100000, new TestNode(-i)); } sw.Stop(); long ms2 = sw.ElapsedMilliseconds; // sw.Reset(); sw.Start(); TestNode latest = null; for (int i = 100000; i >= 0; --i) { tree.Add(latest = new TestNode(0)); } for (int i = 100000; i >= 0; --i) { tree.InsertBefore(latest, new TestNode(i)); } sw.Stop(); long ms1 = sw.ElapsedMilliseconds; //TestNode t1 = new TestNode(1); //TestNode t2 = new TestNode(2); //TestNode t3 = new TestNode(3); //tree.Add(t1); //tree.Add(t2); //tree.Add(t3); //test with linked //test with linked list node LinkedList <TestNode> linkedList = new LinkedList <TestNode>(); sw.Reset(); sw.Start(); for (int i = 100000; i >= 0; --i) { linkedList.AddLast(new TestNode(i)); } sw.Stop(); long ms0 = sw.ElapsedMilliseconds; List <TestNode> nodeList = new List <TestNode>(); sw.Reset(); sw.Start(); for (int i = 100000; i >= 0; --i) { nodeList.Add(new TestNode(i)); } sw.Stop(); long ms5 = sw.ElapsedMilliseconds; }
void Start() { // DEBUG foofoo testing... _targeting = GameObject.Find("Targeting").transform; ChunkGenerator chunkgen = new ChunkGenerator(); var sw = new System.Diagnostics.Stopwatch(); sw.Start(); for (int cx = 0; cx < _world.SizeX; cx++) { for (int cy = 0; cy < _world.SizeY; cy++) { for (int cz = 0; cz < _world.SizeZ; cz++) { var chunk = _world.CreateChunk(new Vector3i(cx, cy, cz), chunkgen); } } } Debug.Log("World generation took " + sw.ElapsedMilliseconds + " ms"); sw.Reset(); sw.Start(); // make some dummy content _world.BeginBatchUpdate(); for (int x = 0; x < _world.SizeX * 16; x++) { int z = 91; _world.SetBlock(new Vector3i(x, 85, z - 2), new BlockType(2)); _world.SetBlock(new Vector3i(x, 85, z - 1), new BlockType(2)); _world.SetBlock(new Vector3i(x, 85, z), new BlockType(2)); _world.SetBlock(new Vector3i(x, 85, z + 1), new BlockType(2)); _world.SetBlock(new Vector3i(x, 85, z + 2), new BlockType(2)); _world.SetBlock(new Vector3i(x, 86, z), new BlockType(0)); _world.SetBlock(new Vector3i(x, 87, z), new BlockType(0)); _world.SetBlock(new Vector3i(x, 88, z), new BlockType(0)); _world.SetBlock(new Vector3i(x, 86, z - 1), new BlockType(0)); _world.SetBlock(new Vector3i(x, 87, z - 1), new BlockType(0)); _world.SetBlock(new Vector3i(x, 86, z + 1), new BlockType(0)); _world.SetBlock(new Vector3i(x, 87, z + 1), new BlockType(0)); // pillars if (x % 6 == 3) { for (int y = 84; y > 0 && _world.GetBlock(new Vector3i(x, y, z)).isTransparent(); y--) { _world.SetBlock(new Vector3i(x, y, z), new BlockType(2)); } } } _world.EndBatchUpdate(); _world.Sunlight.CalculateAll(); // Do initial direct lighting for (int cy = _world.SizeY - 1; cy >= 0; cy--) { for (int cx = 0; cx < _world.SizeX; cx++) { for (int cz = 0; cz < _world.SizeZ; cz++) { ChunkLightmap lightmap = _world.GetLightmap(new Vector3i(cx, cy, cz)); lightmap.ApplyDirectSunlight(); } } } // spread the sunlight all around the place for (int cy = _world.SizeY - 1; cy >= 0; cy--) { for (int cx = 0; cx < _world.SizeX; cx++) { for (int cz = 0; cz < _world.SizeZ; cz++) { ChunkLightmap lightmap = _world.GetLightmap(new Vector3i(cx, cy, cz)); lightmap.PropagateSunlight(); } } } Debug.Log("Sunlight initialization took " + sw.ElapsedMilliseconds + " ms"); sw.Reset(); sw.Start(); foreach (Chunk chunk in _world.Chunks.Values) { _foofoo.Enqueue(chunk); } StartCoroutine(CheckLighting()); }
IEnumerable StringifyAsync(int depth, StringBuilder builder, bool pretty = false) //Convert the JSONObject into a string //Profiler.BeginSample("JSONprint"); { if (depth++ > MAX_DEPTH) { #if UNITY_2 || UNITY_3 || UNITY_4 || UNITY_5 || UNITY_2018 Debug.Log #else Debug.WriteLine #endif ("reached max depth!"); yield break; } if (printWatch.Elapsed.TotalSeconds > maxFrameTime) { printWatch.Reset(); yield return(null); printWatch.Start(); } switch (type) { case Type.BAKED: builder.Append(str); break; case Type.STRING: builder.AppendFormat("\"{0}\"", str); break; case Type.NUMBER: if (useInt) { builder.Append(i.ToString()); } else { #if USEFLOAT if (float.IsInfinity(n)) { builder.Append(INFINITY); } else if (float.IsNegativeInfinity(n)) { builder.Append(NEGINFINITY); } else if (float.IsNaN(n)) { builder.Append(NaN); } #else if (double.IsInfinity(n)) { builder.Append(INFINITY); } else if (double.IsNegativeInfinity(n)) { builder.Append(NEGINFINITY); } else if (double.IsNaN(n)) { builder.Append(NaN); } #endif else { builder.Append(n.ToString()); } } break; case Type.OBJECT: builder.Append("{"); if (list.Count > 0) { #if (PRETTY) //for a bit more readability, comment the define above to disable system-wide if (pretty) { builder.Append(NEWLINE); } #endif for (int i = 0; i < list.Count; i++) { string key = keys[i]; JSONObject obj = list[i]; if (obj) { #if (PRETTY) if (pretty) { for (int j = 0; j < depth; j++) { builder.Append("\t"); //for a bit more readability } } #endif builder.AppendFormat("\"{0}\":", key); foreach (IEnumerable e in obj.StringifyAsync(depth, builder, pretty)) { yield return(e); } builder.Append(","); #if (PRETTY) if (pretty) { builder.Append(NEWLINE); } #endif } } #if (PRETTY) if (pretty) { builder.Length -= 2; } else #endif builder.Length--; } #if (PRETTY) if (pretty && list.Count > 0) { builder.Append(NEWLINE); for (int j = 0; j < depth - 1; j++) { builder.Append("\t"); //for a bit more readability } } #endif builder.Append("}"); break; case Type.ARRAY: builder.Append("["); if (list.Count > 0) { #if (PRETTY) if (pretty) { builder.Append(NEWLINE); //for a bit more readability } #endif for (int i = 0; i < list.Count; i++) { if (list[i]) { #if (PRETTY) if (pretty) { for (int j = 0; j < depth; j++) { builder.Append("\t"); //for a bit more readability } } #endif foreach (IEnumerable e in list[i].StringifyAsync(depth, builder, pretty)) { yield return(e); } builder.Append(","); #if (PRETTY) if (pretty) { builder.Append(NEWLINE); //for a bit more readability } #endif } } #if (PRETTY) if (pretty) { builder.Length -= 2; } else #endif builder.Length--; } #if (PRETTY) if (pretty && list.Count > 0) { builder.Append(NEWLINE); for (int j = 0; j < depth - 1; j++) { builder.Append("\t"); //for a bit more readability } } #endif builder.Append("]"); break; case Type.BOOL: if (b) { builder.Append("true"); } else { builder.Append("false"); } break; case Type.NULL: builder.Append("null"); break; } //Profiler.EndSample(); }
public PlatformSpecificWindow(PlatformSupportAbstract app, PlatformSupportAbstract.PixelFormats format, PlatformSupportAbstract.ERenderOrigin RenderOrigin) { m_app = app; m_format = format; m_sys_format = PlatformSupportAbstract.PixelFormats.Undefined; m_RenderOrigin = RenderOrigin; m_WindowContentNeedsRedraw = true; m_StopWatch = new Stopwatch(); switch (m_format) { case PlatformSupportAbstract.PixelFormats.BlackWhite: m_sys_format = PlatformSupportAbstract.PixelFormats.BlackWhite; break; case PlatformSupportAbstract.PixelFormats.Gray8: m_sys_format = PlatformSupportAbstract.PixelFormats.Gray8; break; case PlatformSupportAbstract.PixelFormats.Gray16: m_sys_format = PlatformSupportAbstract.PixelFormats.Gray16; break; case PlatformSupportAbstract.PixelFormats.Rgb565: case PlatformSupportAbstract.PixelFormats.Rgb555: m_sys_format = PlatformSupportAbstract.PixelFormats.Rgb555; break; case PlatformSupportAbstract.PixelFormats.RgbAAA: case PlatformSupportAbstract.PixelFormats.BgrAAA: case PlatformSupportAbstract.PixelFormats.RgbBBA: case PlatformSupportAbstract.PixelFormats.BgrABB: m_sys_format = PlatformSupportAbstract.PixelFormats.Bgr24; break; case PlatformSupportAbstract.PixelFormats.Rgb24: m_sys_format = PlatformSupportAbstract.PixelFormats.Rgb24; break; case PlatformSupportAbstract.PixelFormats.Bgr24: m_sys_format = PlatformSupportAbstract.PixelFormats.Bgr24; break; case PlatformSupportAbstract.PixelFormats.Rgb48: case PlatformSupportAbstract.PixelFormats.Bgr48: m_sys_format = PlatformSupportAbstract.PixelFormats.Bgr24; break; case PlatformSupportAbstract.PixelFormats.Bgra32: m_sys_format = PlatformSupportAbstract.PixelFormats.Bgra32; break; case PlatformSupportAbstract.PixelFormats.Abgr32: m_sys_format = PlatformSupportAbstract.PixelFormats.Abgr32; break; case PlatformSupportAbstract.PixelFormats.Argb32: m_sys_format = PlatformSupportAbstract.PixelFormats.Argb32; break; case PlatformSupportAbstract.PixelFormats.Rgba32: m_sys_format = PlatformSupportAbstract.PixelFormats.Rgba32; break; case PlatformSupportAbstract.PixelFormats.Bgra64: case PlatformSupportAbstract.PixelFormats.Abgr64: case PlatformSupportAbstract.PixelFormats.Argb64: case PlatformSupportAbstract.PixelFormats.Rgba64: m_sys_format = PlatformSupportAbstract.PixelFormats.Bgra32; break; } m_StopWatch.Reset(); m_StopWatch.Start(); }
void Init() { PlayerInfo playerInfo = new PlayerInfo { id = 1001, name = "lfwu", buffList = new List <Buff> { new Buff { id = 1001001, description = "this buff can reduce speed", baseAttack = 20.0, canRepeat = false }, new Buff { id = 1001002, description = "this buff can increase physic attack", baseAttack = 0, canRepeat = true } } }; string litJsonStr = string.Empty; string unityJsonStr = string.Empty; System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); int count = 1000; sw.Start(); for (var i = 0; i < count; ++i) { litJsonStr = JsonMapper.ToJson(playerInfo); } Debug.Log("LitJson Serialize use time:" + sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); for (var i = 0; i < count; ++i) { unityJsonStr = JsonUtility.ToJson(playerInfo); } Debug.Log("UnityJson Serialize use time:" + sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); for (var i = 0; i < count; ++i) { PlayerInfo litPlayerInfo = JsonMapper.ToObject <PlayerInfo>(litJsonStr); } Debug.Log("LitJson Deserialzie use time:" + sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); for (var i = 0; i < count; ++i) { PlayerInfo unityJsonInfo = JsonUtility.FromJson <PlayerInfo>(litJsonStr); } Debug.Log("UnityJson Deserialize use time:" + sw.ElapsedMilliseconds); Debug.Log("unity string len:" + unityJsonStr.Length + ", litjson string len:" + litJsonStr.Length); }
static void Main(string[] args) { var resbof = BiserObjectify.Generator.Run(typeof(TS6), true, @"D:\Temp\1\", forBiserBinary: true, forBiserJson: true); return; TS6 t6 = new TS6() { //P1 = "dsfs", //P2 = 456, //P3 = DateTime.UtcNow, //P4 = new List<Dictionary<DateTime, Tuple<int, string>>> // { // new Dictionary<DateTime, Tuple<int, string>>{ // { DateTime.UtcNow.AddMinutes(-1), new Tuple<int, string>(12,"pipec") }, // { DateTime.UtcNow.AddMinutes(-2), new Tuple<int, string>(125,"pipec123") } // }, // new Dictionary<DateTime, Tuple<int, string>>{ // { DateTime.UtcNow.AddMinutes(-3), new Tuple<int, string>(17,"pihfpec") }, // { DateTime.UtcNow.AddMinutes(-4), new Tuple<int, string>(15625,"pipfghec123") } // } // }, //P5 = new Dictionary<int, Tuple<int, string>> { // { 12, new Tuple<int, string>(478,"dsffdf") }, // { 178, new Tuple<int, string>(5687,"sdfsd") } // }, //P6 = new Tuple<int, string, Tuple<List<string>, DateTime>>(445, "dsfdfgfgfg", //new Tuple<List<string>, DateTime>(new List<string> { "a1", "a2" }, DateTime.Now.AddDays(58))), //P7 = new List<string> { "fgdfgrdfg", "dfgfdgdfg" }, //P8 = new Dictionary<int, List<string>> { // { 34,new List<string> { "drtttz","ghhtht"} }, // { 4534,new List<string> { "dfgfghfgz","6546ghhtht"} } // }, //P13 = new List<List<int>> { new List<int> { 12, 43, 54 }, new List<int> { 12, 43, 54 } }, //P15 = new Tuple<int, string, DateTime, byte[]>(147, "sdffgfdsg", DateTime.UtcNow, new byte[] { 45, 78, 95 }), //P16 = new List<Dictionary<int, Tuple<int, string>>> // { // new Dictionary<int, Tuple<int, string>>{ // { 1, new Tuple<int, string>(12,"pipec") }, // { 2, new Tuple<int, string>(125,"pipec123") } // }, // new Dictionary<int, Tuple<int, string>>{ // { 3, new Tuple<int, string>(17,"pihfpec") }, // { 4, new Tuple<int, string>(15625,"pipfghec123") } // } // }, //P17 = new int[3] { 12, 3545, 7987 } }; #region "pars" //t6.P19 = new Dictionary<int, List<string>>[2][]; //t6.P19[0] = new Dictionary<int, List<string>>[3]; //t6.P19[1] = new Dictionary<int, List<string>>[5]; //t6.P19[0][0] = new Dictionary<int, List<string>> { { 1, new List<string> { "dsf", "dsfd" } }, { 3, new List<string> { "fdsf", "tzutr" } } }; //t6.P11 = new int[2][]; //t6.P11[0] = new int[3]; //t6.P11[1] = new int[3]; //t6.P11[0][0] = 12; //t6.P11[0][1] = 14; //t6.P11[1][0] = 125; //t6.P11[1][2] = 19; //t6.P18 = new List<int>[2, 3, 4]; //t6.P18[0, 0, 0] = new List<int> { 1, 2 }; //t6.P18[0, 0, 1] = new List<int> { 12, 4 }; //t6.P18[0, 1, 0] = new List<int> { 3, 12, 7, 8 }; //t6.P18[0, 1, 1] = new List<int> { 99, 14, 7, 7 }; //t6.P18[1, 0, 0] = new List<int> { 4, 17, 9, 9, 9, 6 }; //t6.P18[1, 0, 1] = new List<int> { 2, 12, 5, 0 }; //t6.P12 = new int[2, 3, 4]; //t6.P12[0, 0, 0] = 12; //t6.P12[0, 0, 1] = 13; //t6.P12[0, 1, 0] = 14; //t6.P12[0, 1, 1] = 15; //t6.P12[1, 0, 0] = 16; //t6.P12[1, 0, 1] = 17; //t6.P121 = new string[2, 3, 4]; //t6.P121[0, 0, 0] = "dsf"; //t6.P121[0, 0, 1] = "dsf"; //t6.P121[0, 1, 0] = "dsf"; //t6.P121[0, 1, 1] = "dsf"; //t6.P121[1, 0, 0] = "dsf"; //t6.P121[1, 0, 1] = "dsf"; //var ar1 = new int[2, 3, 4]; //ar1[0, 0, 0] = 12; //ar1[0, 0, 1] = 13; //ar1[0, 1, 0] = 14; //ar1[0, 1, 1] = 15; //ar1[1, 0, 0] = 16; //ar1[1, 0, 1] = 17; //t6.P21 = new List<int[,,]>(); //t6.P21.Add(ar1); //ar1 = new int[2, 3, 4]; //ar1[0, 0, 0] = 12; //ar1[0, 0, 1] = 13; //ar1[0, 1, 0] = 14; //ar1[0, 1, 1] = 15; //ar1[1, 0, 0] = 16; //ar1[1, 0, 1] = 17; //ar1[0, 0, 0] = 122; //ar1[0, 0, 1] = 132; //t6.P21.Add(ar1); #endregion //Json test //t6.P25 = new System.Collections.Generic.Dictionary<System.Int32, System.Collections.Generic.List<System.String[,][][,,]>> // [2, 3, 4, 8][][,,]; //var njSer = NetJSON.NetJSON.Serialize(t6, new NetJSON.NetJSONSettings { DateFormat = NetJSON.NetJSONDateFormat.ISO }); //var jsonSet = new Biser.JsonSettings { DateFormat = Biser.JsonSettings.DateTimeStyle.ISO }; //Biser.JsonEncoder enc = new Biser.JsonEncoder(t6, jsonSet); //string es = enc.GetJSON(Biser.JsonSettings.JsonStringStyle.Prettify); //var ot2 = TS6.BiserJsonDecode(es, settings: jsonSet); ////var ot2 = TS6.BiserJsonDecode(njSer, settings: jsonSet); //Binary test //var encb = t6.BiserEncoder().Encode(); //var t6n = TS6.BiserDecode(encb); return; TestDecodeV1(); return; //var jsres = NetJSON.NetJSON.Serialize((int)12); //12 //var ojsres = NetJSON.NetJSON.Deserialize<int>(jsres); //var jsres2 = NetJSON.NetJSON.Serialize((double)12.45687); //12.45687 //var ojsres2 = NetJSON.NetJSON.Deserialize<double>(jsres2); //Dictionary<string, byte[]> dic1d = new Dictionary<string, byte[]>(); //dic1d.Add("str1", new byte[] { 1, 2, 3 }); //dic1d.Add("str2", new byte[] { 1, 2 }); //dic1d.Add("str3", null); //var jsres1 = NetJSON.NetJSON.Serialize(dic1d); //{"str1":"AQID","str2":"AQI=","str3":null} //var ojsres1 = NetJSON.NetJSON.Deserialize<Dictionary<string, byte[]>>(jsres1); //List<Dictionary<string, byte[]>> ldic1d = new List<Dictionary<string, byte[]>>(); //ldic1d.Add(dic1d); //ldic1d.Add(dic1d); //var jsres3 = NetJSON.NetJSON.Serialize(ldic1d); //[{"str1":"AQID","str2":"AQI=","str3":null},{"str1":"AQID","str2":"AQI=","str3":null}] //var ojsres3 = NetJSON.NetJSON.Deserialize<List<Dictionary<string, byte[]>>>(jsres3); //var jsres4 = NetJSON.NetJSON.Serialize((string)"ds\"fs{d}f"); //"ds\"fs{d}f" //// var jsres4 = NetJSON.NetJSON.Serialize("dsf\"sdfdsf{fdgdfgdf{dsfdsf[sdf\"\"dfdsf}"); //"dsf\"sdfdsf{fdgdfgdf{dsfdsf[sdf\"\"dfdsf}" //var ojsres4 = NetJSON.NetJSON.Deserialize<string>(jsres4); //"ds"fsdf" TS2 jts2 = new TS2() { P1 = long.MinValue, P2 = 4587.4564, P3 = new List <TS3> { new TS3 { P3 = DateTime.UtcNow.AddDays(-1) }, null, //new TS3 { P3 = DateTime.UtcNow.AddDays(-2) }, new TS3 { P3 = DateTime.UtcNow.AddDays(-3) } }, P4 = new TS3 { P1 = "hi" }, P5 = 111 }; //TS1 jts1 = new TS1() //{ // P1 = 12, // P2 = 15, // P3 = 478.5879m, // P4 = new List<TS2> { jts2, jts2 }, // P5 = new Dictionary<long, TS3> { // { 1, new TS3{ P1 = "t1" } }, // { 2, new TS3{ P1 = "t2" } }, // { 3, new TS3{ P1 = "t3" } } // }, // P6 = new Dictionary<uint, List<TS3>> { // { 1, new List<TS3>{ new TS3 { P1 = "h1" }, new TS3 { P1 = "h2" }, new TS3 { P1 = "h3" } } }, // { 2, new List<TS3>{ new TS3 { P1 = "h2" }, new TS3 { P1 = "h2" }, new TS3 { P1 = "h4" } } }, // { 3, new List<TS3>{ new TS3 { P1 = "h3" }, new TS3 { P1 = "h2" }, new TS3 { P1 = "h5" } } }, // { 4, new List<TS3>{ new TS3 { P1 = "h4" }, new TS3 { P1 = "h2" }, new TS3 { P1 = "h6" } } } // }, // P7 = new TS2 { P1 = -789 }, // P8 = new List<Tuple<string, byte[], TS3>> { // new Tuple<string, byte[], TS3>("tt1",new byte[] { 1,2,3},new TS3 { P1 = "z1" }), // new Tuple<string, byte[], TS3>("tt2",new byte[] { 3,2,3},new TS3 { P1 = "z2" }), // new Tuple<string, byte[], TS3>("tt3",new byte[] { 4,2,3},new TS3 { P1 = "z3" }), // }, // P9 = new Tuple<float, TS2, TS3, decimal?>(-.8f, new TS2 { P2 = 45 }, new TS3 { P2 = 12 }, -58.8m), // P10 = "dsf\"sdfdsf{fdgdfgdf{dsfdsf[sdf\"\"dfdsf}" //}; //var jsres5 = NetJSON.NetJSON.Serialize(jts1, new NetJSON.NetJSONSettings { DateFormat = NetJSON.NetJSONDateFormat.ISO, Format = NetJSON.NetJSONFormat.Prettify }); ///*{"P1":12,"P2":15,"P3":478.5879,"P4":[{"P1":-9223372036854775808,"P2":4587.4564,"P3":[{"P3":"\/Date(15340651396274201)\/"},null,{"P3":"\/Date(15338923396274201)\/"}],"P4":{"P1":"hi"},"P5":111},{"P1":-9223372036854775808,"P2":4587.4564,"P3":[{"P3":"\/Date(15340651396274201)\/"},null,{"P3":"\/Date(15338923396274201)\/"}],"P4":{"P1":"hi"},"P5":111}],"P5":{"1":{"P1":"t1"},"2":{"P1":"t2"},"3":{"P1":"t3"}},"P6":{"1":[{"P1":"h1"},{"P1":"h2"},{"P1":"h3"}],"2":[{"P1":"h2"},{"P1":"h2"},{"P1":"h4"}],"3":[{"P1":"h3"},{"P1":"h2"},{"P1":"h5"}],"4":[{"P1":"h4"},{"P1":"h2"},{"P1":"h6"}]},"P7":{"P1":-789},"P8":[{"Item1":"tt1","Item2":"AQID","Item3":{"P1":"z1"}},{"Item1":"tt2","Item2":"AwID","Item3":{"P1":"z2"}},{"Item1":"tt3","Item2":"BAID","Item3":{"P1":"z3"}}],"P9":{"Item1":12.8,"Item2":{"P2":45},"Item3":{"P2":12},"Item4":-58.8}}*/ //var ojsres5 = NetJSON.NetJSON.Deserialize<TS1>(jsres5); //"ds"fsdf" //Dictionary<int, byte[]> dic1d2 = new Dictionary<int, byte[]>(); //key will be transformed toString, so key can't be byte[] //dic1d2.Add(12, new byte[] { 1, 2, 3 }); //dic1d2.Add(17, new byte[] { 1, 2 }); //var jsres6 = NetJSON.NetJSON.Serialize(dic1d2); //{"12":"AQID","17":"AQI="} //var ojsres6 = NetJSON.NetJSON.Deserialize<Dictionary<int, byte[]>>(jsres6); //Dictionary<int, string> dic1d3 = new Dictionary<int, string>(); //key will be transformed toString, so key can't be byte[] //dic1d3.Add(12, "dsf\"sdfdsf{fdgdfgdf{dsfdsf[sdf\"\"dfdsf}"); //dic1d3.Add(17, "dsf\"sdfdsf{fdgddddf{dsfdsf[sdf\"\"dfdsf}"); //var jsres7 = NetJSON.NetJSON.Serialize(dic1d3, new NetJSON.NetJSONSettings { DateFormat = NetJSON.NetJSONDateFormat.ISO, Format = NetJSON.NetJSONFormat.Prettify }); //{"12":"AQID","17":"AQI="} //var ojsres7 = NetJSON.NetJSON.Deserialize<Dictionary<int, string>>(jsres7); ////var jsres8 = NetJSON.NetJSON.Serialize((int?)null); //{"12":"AQID","17":"AQI="} ////var ojsres8 = NetJSON.NetJSON.Deserialize<int?>(jsres8); ////var jsres8 = NetJSON.NetJSON.Serialize("dsf\"sdfdsf{fdgdfgdf{dsfdsf[sdf\"\"dfdsf}"); //{"12":"AQID","17":"AQI="} ////var ojsres8 = NetJSON.NetJSON.Deserialize<string>(jsres8); ////Dictionary<int, int> dic1d4 = new Dictionary<int, int>(); //key will be transformed toString, so key can't be byte[] ////dic1d4.Add(12, 15); ////dic1d4.Add(17, 57); ////var jsres8 = NetJSON.NetJSON.Serialize(dic1d4); //{"12":"AQID","17":"AQI="} ////var ojsres8 = NetJSON.NetJSON.Deserialize<Dictionary<int, int>>(jsres8); //List<int> dic1d4 = new List<int>(); //dic1d4.Add(324); //dic1d4.Add(33); //var jsres8 = NetJSON.NetJSON.Serialize(dic1d4); //{"12":"AQID","17":"AQI="} ////var ojsres8 = NetJSON.NetJSON.Deserialize<List<int, int>>(jsres8); //JsonDecoder jsdec = new JsonDecoder(jsres8); //{"12":15,"17":57} ////var iuz = jsdec.GetInt_NULL(); ////var iuz = jsdec.GetString(); ////Dictionary<int,int> iuzd = jsdec.CheckNull() ? null : new Dictionary<int, int>(); //List<int> iuzd = jsdec.CheckNull() ? null : new List<int>(); //if (iuzd != null) //{ // //jsdec.GetCollection(() => { return jsdec.GetInt(); }, // // () => { return jsdec.GetInt(); }, iuzd, true); // //foreach (var item in iuzd) // // Debug.WriteLine(item.Key); // jsdec.GetCollection(() => { return jsdec.GetInt(); }, iuzd, true); // foreach (var item in iuzd) // Debug.WriteLine(item); //} TS1 jsts1 = new TS1() { P1 = 12, P2 = 17, P3 = 478.5879m, P4 = new List <TS2> { jts2, jts2 }, //P5 = new Dictionary<long, TS3> { // { 1, new TS3{ P1 = "t1" } }, // { 2, new TS3{ P1 = "t2" } }, // { 3, new TS3{ P1 = "t3" } } // }, P6 = new Dictionary <uint, List <TS3> > { { 1, new List <TS3> { new TS3 { P1 = "h1" }, new TS3 { P1 = "h2" }, new TS3 { P1 = "h3" } } }, { 2, new List <TS3> { new TS3 { P1 = "h2" }, new TS3 { P1 = "h2" }, new TS3 { P1 = "h4" } } }, { 3, new List <TS3> { new TS3 { P1 = "h3" }, new TS3 { P1 = "h2" }, new TS3 { P1 = "h5" } } }, { 4, new List <TS3> { new TS3 { P1 = "h4" }, new TS3 { P1 = "h2" }, new TS3 { P1 = "h6" } } } }, P7 = new TS2 { P1 = -789 }, P8 = new List <Tuple <string, byte[], TS3> > { new Tuple <string, byte[], TS3>("tt1", new byte[] { 1, 2, 3 }, new TS3 { P1 = "z1" }), new Tuple <string, byte[], TS3>("tt2", new byte[] { 3, 2, 3 }, new TS3 { P1 = "z2" }), new Tuple <string, byte[], TS3>("tt3", new byte[] { 4, 2, 3 }, new TS3 { P1 = "z3" }), }, P9 = new Tuple <float, TS2, TS3, decimal?>(-.8f, new TS2 { P2 = 45 }, new TS3 { P2 = 12 }, -58.8m), }; jsts1.P11 = new Dictionary <int, int>(); jsts1.P11.Add(12, 14); jsts1.P11.Add(17, 89); //jsts1.P14 = new Dictionary<int, int>(); //jsts1.P14.Add(17, 14); //jsts1.P14.Add(19, 89); jsts1.P5 = new Dictionary <long, TS3>(); jsts1.P5.Add(189, new TS3 { P1 = "dsf", P2 = 45, P3 = DateTime.UtcNow }); jsts1.P5.Add(178, new TS3 { P1 = "sdfsdfsdfs", P2 = null, P3 = DateTime.UtcNow }); jsts1.P5.Add(148, new TS3 { P1 = "dfdff", P2 = null, P3 = DateTime.UtcNow }); jsts1.P12 = 789; jsts1.P13 = new List <TS3>(); jsts1.P13.Add(new TS3 { P1 = "dsf", P2 = 45, P3 = DateTime.UtcNow }); jsts1.P13.Add(new TS3 { P1 = "sdfsdfsdfs", P2 = null, P3 = DateTime.UtcNow }); jsts1.P15 = new List <List <TS3> >(); jsts1.P15.Add(jsts1.P13); jsts1.P15.Add(jsts1.P13); jsts1.P16 = new Dictionary <long, List <TS3> >(); jsts1.P16.Add(12, jsts1.P13); jsts1.P16.Add(14, jsts1.P13); jsts1.P16.Add(28, jsts1.P13); jsts1.P18 = new List <int>(); jsts1.P18.Add(178); jsts1.P18.Add(912); jsts1.P19 = new Tuple <int, TS3>(12, new TS3 { P1 = "dsf", P2 = 45, P3 = DateTime.UtcNow }); jsts1.P17 = new DateTime(2018, 6, 5, 17, 44, 15, 443, DateTimeKind.Utc); //var jsres9 = NetJSON.NetJSON.Serialize(jsts1, new NetJSON.NetJSONSettings() { Format = NetJSON.NetJSONFormat.Prettify }); var jsres9 = NetJSON.NetJSON.Serialize(jsts1, new NetJSON.NetJSONSettings() { Format = NetJSON.NetJSONFormat.Prettify, DateFormat = NetJSON.NetJSONDateFormat.Default }); var njdv1 = NetJSON.NetJSON.Deserialize <TS1>(jsres9, new NetJSON.NetJSONSettings() { //Format = NetJSON.NetJSONFormat.Prettify, DateFormat = NetJSON.NetJSONDateFormat.Default }); //var jsres9 = NetJSON.NetJSON.Serialize(jsts1); TS1 jsts1d = null; //jsts1d = TS1.BiserJsonDecode(jsres9, null, new JsonSettings { DateFormat = JsonSettings.DateTimeStyle.ISO }); //----------------- //var jsres91 = NetJSON.NetJSON.Serialize(jsts1.P13, new NetJSON.NetJSONSettings() //{ //Format = NetJSON.NetJSONFormat.Prettify, // DateFormat = NetJSON.NetJSONDateFormat.ISO //}); JsonEncoder jenc = new JsonEncoder(null, new JsonSettings { DateFormat = JsonSettings.DateTimeStyle.Default, JsonStringFormat = JsonSettings.JsonStringStyle.Prettify }); // jsts1.BiserJsonEncode(jenc); string wow1 = jenc.GetJSON(); var jsts1d1 = TS1.BiserJsonDecode(wow1, null, new JsonSettings { DateFormat = JsonSettings.DateTimeStyle.Default }); //TestJSONv1(); //StreamReader sr=new StreamReader("",Encoding.UTF8) //StreamWriter sw=new StreamWriter() Console.WriteLine("Press to start test"); Console.ReadLine(); System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); sw.Start(); for (int i = 0; i < 10000; i++) { jenc = new JsonEncoder(new JsonSettings { DateFormat = JsonSettings.DateTimeStyle.Default, JsonStringFormat = JsonSettings.JsonStringStyle.Default }); jsts1.BiserJsonEncode(jenc); wow1 = jenc.GetJSON(); } sw.Stop(); Console.WriteLine($"Biser encode: {sw.ElapsedMilliseconds} ms"); sw.Reset(); sw.Start(); for (int i = 0; i < 10000; i++) { jsres9 = NetJSON.NetJSON.Serialize(jsts1, new NetJSON.NetJSONSettings() { Format = NetJSON.NetJSONFormat.Default, DateFormat = NetJSON.NetJSONDateFormat.Default }); } sw.Stop(); Console.WriteLine($"NetJSON encode: {sw.ElapsedMilliseconds} ms"); sw.Reset(); sw.Start(); for (int i = 0; i < 10000; i++) { jsts1d = TS1.BiserJsonDecode(wow1, null, new JsonSettings { DateFormat = JsonSettings.DateTimeStyle.Default }); } sw.Stop(); Console.WriteLine($"Biser decode: {sw.ElapsedMilliseconds} ms"); sw.Reset(); sw.Start(); for (int i = 0; i < 10000; i++) { jsts1d = NetJSON.NetJSON.Deserialize <TS1>(jsres9); } sw.Stop(); Console.WriteLine($"NetJSON decode: {sw.ElapsedMilliseconds} ms"); sw.Reset(); // jsts1d = TS1.BiserJsonDecode(jsres9); Console.ReadLine(); return; Biser.Encoder en2 = new Biser.Encoder(); en2.Add((int)12); Dictionary <string, byte[]> dic1 = new Dictionary <string, byte[]>(); dic1.Add("str1", new byte[] { 1, 2, 3 }); dic1.Add("str2", new byte[] { 1, 2 }); dic1.Add("str3", null); dic1.Add("str4", new byte[0]); dic1.Add("str5", new byte[] { 1, 2, 3, 4, 5 }); en2.Add(dic1, r => { en2.Add(r.Key); en2.Add(r.Value); }); //List<int> lst1 = new List<int>(); //lst1.Add(1); //lst1.Add(2); //lst1.Add(3); //en2.Add(lst1, r => { en2.Add(r); }); en2.Add((int)14); Biser.Decoder de2 = new Biser.Decoder(en2.Encode()); Debug.WriteLine(de2.GetInt()); //List<int> lst = de2.CheckNull() ? null : new List<int>(); //if (lst != null) //{ // de2.GetCollection(() => { return de2.GetInt(); }, lst, true); // foreach (var item in lst) // Debug.WriteLine(item); //} Dictionary <string, byte[]> dic = de2.CheckNull() ? null : new Dictionary <string, byte[]>(); if (dic != null) { de2.GetCollection(() => { return(de2.GetString()); }, () => { return(de2.GetByteArray()); }, dic, true); foreach (var item in dic) { Debug.WriteLine(item.Key); } } Debug.WriteLine(de2.GetInt()); return; //var le = BitConverter.IsLittleEndian; Biser.Encoder enn = new Biser.Encoder(); byte[] btEnn = null; double flv = -17.32; enn.Add(flv); //enn.Add((long)1); btEnn = enn.Encode(); var res = true ^ false; //BitConverter.ToDouble() var fltBts = BitConverter.GetBytes(flv); return; //enn.Add((long)-123879); enn.Add((ulong)1521797378957); btEnn = enn.Encode(); long tr = 1521797378957; do { tr = tr >> 7; Console.WriteLine("М " + tr); } while (tr != 0); Biser.Decoder denn = new Biser.Decoder(btEnn); //var hzj = denn.GetLong(); var hzj = denn.GetULong(); var tt = Biser.Biser.EncodeZigZag((long)-123879, 64); var value = -123879; var tt1 = (value << 1) ^ (value >> 63); var tt2 = Biser.Biser.DecodeZigZag((ulong)tt1); Console.WriteLine("L=" + (value << 1)); Console.WriteLine("R=" + (value >> 63)); Console.WriteLine("T=" + tt1 + "; dec=" + tt2); Console.WriteLine("tmp=" + (100000000000 & 0x7fffffff)); Console.WriteLine("tmp=" + ((-100000000000) & 0x7fffffff)); /* * var v1 = 123879; * var hi = 0x80000000; * var low = 0x7fffffff; * var hi1 = ~~(v1 / hi); * var low1 = v1 & low; * var v1b = hi1 * hi + low1; */ //var tm = new DateTime(1521797378957*10000, DateTimeKind.Utc); var tm = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc) .AddMilliseconds(1521797378957); // for (int i = 0; i < 256; i++) { //Console.WriteLine((sbyte)(i) + " _ " + (i & 0x80)+ " _ " + i + " _ " + (i - (i&0x80))); sbyte p = (sbyte)(i); sbyte s = (sbyte)(i); byte b = (byte)((p + 128) + (1 - 2 * (((p + 128) & 0x80) >> 7)) * 128); byte b1 = (byte)(s + (256 & ((s & 0x80) << 1))); Console.WriteLine(i + " _ " + (sbyte)(i) + " _ " + (i - ((i & 128) << 1)) + " _ " + b + " _> " + b1 ); //128 0x80 byte to sbyte converter } //double flv = 12.56; //double flv = 124.56; var uBts = BitConverter.ToUInt64(fltBts, 0); return; //float flv = 12.56f; //flv = 0; //flv = float.MinValue; //flv = float.MaxValue; //var fltBts = BitConverter.GetBytes(flv); //var uBts = BitConverter.ToUInt32(fltBts, 0); return; TS3 ts3 = new TS3() { P1 = "welldone", P2 = null, P3 = DateTime.UtcNow }; //var bt3 = ts3.BiserEncoder().Encode(); //TS3 ts2D = TS3.BiserDecode(bt3); TS2 ts2 = new TS2() { P1 = long.MinValue, P2 = 4587.4564, P3 = new List <TS3> { new TS3 { P3 = DateTime.UtcNow.AddDays(-1) }, null, //new TS3 { P3 = DateTime.UtcNow.AddDays(-2) }, new TS3 { P3 = DateTime.UtcNow.AddDays(-3) } }, P4 = new TS3 { P1 = "hi" }, P5 = 111 }; //var bt2 = ts2.BiserEncoder().Encode(); //TS2 ts2D = TS2.BiserDecode(bt2); TS1 ts1 = new TS1() { P1 = 12, P2 = 15, P3 = 478.5879m, P4 = new List <TS2> { ts2, ts2 }, P5 = new Dictionary <long, TS3> { { 1, new TS3 { P1 = "t1" } }, { 2, new TS3 { P1 = "t2" } }, { 3, new TS3 { P1 = "t3" } } }, P6 = new Dictionary <uint, List <TS3> > { { 1, new List <TS3> { new TS3 { P1 = "h1" }, new TS3 { P1 = "h2" }, new TS3 { P1 = "h3" } } }, { 2, new List <TS3> { new TS3 { P1 = "h2" }, new TS3 { P1 = "h2" }, new TS3 { P1 = "h4" } } }, { 3, new List <TS3> { new TS3 { P1 = "h3" }, new TS3 { P1 = "h2" }, new TS3 { P1 = "h5" } } }, { 4, new List <TS3> { new TS3 { P1 = "h4" }, new TS3 { P1 = "h2" }, new TS3 { P1 = "h6" } } } }, P7 = new TS2 { P1 = -789 }, P8 = new List <Tuple <string, byte[], TS3> > { new Tuple <string, byte[], TS3>("tt1", new byte[] { 1, 2, 3 }, new TS3 { P1 = "z1" }), new Tuple <string, byte[], TS3>("tt2", new byte[] { 3, 2, 3 }, new TS3 { P1 = "z2" }), new Tuple <string, byte[], TS3>("tt3", new byte[] { 4, 2, 3 }, new TS3 { P1 = "z3" }), }, P9 = new Tuple <float, TS2, TS3, decimal?>(12.8f, new TS2 { P2 = 45 }, new TS3 { P2 = 12 }, -58.8m) }; var bt1 = ts1.BiserEncoder().Encode(); TS1 ts1D = TS1.BiserDecode(bt1); //TestMultiDimensionArray //TestCustom(); //TestPrimitives(); //TestBE1(); TestT5(); //TestListDictionary(); Console.ReadLine(); //var enc = new Biser.Encoder(); //enc.Add(double.MinValue); //enc.Add(double.MaxValue); //enc.Add((double)-455.45); //enc.Add((double)465.45); //var decoder = new Biser.Decoder(enc.Encode()); //var d1 = decoder.GetDouble(); //var d2 = decoder.GetDouble(); //var d3 = decoder.GetDouble(); //var d4 = decoder.GetDouble(); //var enc = new Biser.Encoder(); //enc.Add(float.MinValue); //enc.Add(float.MaxValue); //enc.Add((float)-455.45); //enc.Add((float)465.45); //var decoder = new Biser.Decoder(enc.Encode()); //var d1 = decoder.GetFloat(); //var d2 = decoder.GetFloat(); //var d3 = decoder.GetFloat(); //var d4 = decoder.GetFloat(); }
public Timer() { stopwatch = new System.Diagnostics.Stopwatch(); stopwatch.Reset(); stopwatch.Start(); }
public override void OnModuleDisabled() { stopwatch.Stop(); stopwatch.Reset(); }
//flick()に関するメソッド void flick() { //フリック判定時間OKなら //注意:if (hanteiSorF() == true)は何故か別のifで囲まないと働かない if (hanteiSorF() == true) { //flickMoveがtrue、マウスボタンを上げた時、 //共通変数のbuttonmoveがfalseならば(←これないと、ボタン移動の時バグる) if ((flickMove == false) && (Input.GetMouseButtonUp(0) && (kyotu.bottomMove == false))) { //k6_aa:ストップウォッチスタート Fstopwatch.Start(); flickMove = true; } } //flickMoveがtrueなら if (flickMove == true) { //flick中にタップがあったらflickを止める if (Input.GetMouseButtonDown(0)) { flickElapse = fjikan; } if (fjikan > flickElapse) { //この中に時間内にしたい処理を書く。------ //diffがプラスかマイナスかによって上下の方向が決まる float diff = atoClick.x - saishoClick.x; //ワールド座標の絶対値が1.5以上の時のみフリックをする。 if (!(diff <= 1.5 && diff >= -1.5)) { //mainCameraPosi=1つまり目次なら if (kyotu.mainCameraPosi == 1) { //diffがマイナスなら、つまり→移動判定のみ if (diff <= 0) { //mainCameraのx位置が5.6以下ならば if (this.gameObject.transform.position.x <= 5.6) { this.gameObject.transform.position += new Vector3(-chousei * diff * Time.deltaTime, 0, 0); } else { //最終的に行く位置 this.gameObject.transform.position = new Vector3(5.6f, this.gameObject.transform.position.y, this.gameObject.transform.position.z ); kyotu.mainCameraPosi = 2; //スワイプ終了処理 // k6_ab:ストップウォッチの時間をリセット Fstopwatch.Reset(); flickMove = false; } } } else if (kyotu.mainCameraPosi == 2) { //ポジ2からポジ1への横移動 //diffがプラスなら、つまり左移動判定のみ if (diff >= 0) { //mainCameraのx位置が5.6以下ならば if (this.gameObject.transform.position.x >= 0) { this.gameObject.transform.position += new Vector3(-chousei * diff * Time.deltaTime, 0, 0); } else { //最終的に行く位置 this.gameObject.transform.position = new Vector3(0, this.gameObject.transform.position.y, this.gameObject.transform.position.z ); kyotu.mainCameraPosi = 1; //スワイプ終了処理 // k6_ab:ストップウォッチの時間をリセット Fstopwatch.Reset(); flickMove = false; } } //ポジ2からポジ3への横移動 //diffがマイナスなら、つまり右移動判定のみ else if (diff < 0) { //mainCameraのx位置が5.6以下ならば if (this.gameObject.transform.position.x <= 11.2f) { this.gameObject.transform.position += new Vector3(-chousei * diff * Time.deltaTime, 0, 0); } else { //最終的に行く位置 this.gameObject.transform.position = new Vector3(11.2f, this.gameObject.transform.position.y, this.gameObject.transform.position.z ); kyotu.mainCameraPosi = 3; //スワイプ終了処理 // k6_ab:ストップウォッチの時間をリセット Fstopwatch.Reset(); flickMove = false; } } } else if (kyotu.mainCameraPosi == 3) { //ポジ3からポジ2への横移動 //diffがプラスなら、つまり左移動判定のみ if (diff >= 0) { //mainCameraのx位置が5.6以下ならば if (this.gameObject.transform.position.x >= 5.6) { this.gameObject.transform.position += new Vector3(-chousei * diff * Time.deltaTime, 0, 0); } else { //最終的に行く位置 this.gameObject.transform.position = new Vector3(5.6f, this.gameObject.transform.position.y, this.gameObject.transform.position.z ); kyotu.mainCameraPosi = 2; //スワイプ終了処理 // k6_ab:ストップウォッチの時間をリセット Fstopwatch.Reset(); flickMove = false; } } } } else { //スワイプ終了処理 //k6_ab:ストップウォッチの時間をリセット Fstopwatch.Reset(); flickMove = false; } } } }
/// <summary> /// TouchesBegan /// </summary> /// <param name="touches">touches</param> protected override void TouchesBegan(System.Collections.Generic.IEnumerable <GestureTouch> touches) { stopWatch.Reset(); stopWatch.Start(); }
//Sending thread private void SendingTask() { //Connect to the server ConnectToServer(); //If this was killed early, exit now if (_shouldExit) { return; } //Prepare for main thread System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); long timeElapsed = 0; byte[] numBuf; byte[] positionBytes = new byte[16]; string text; List <byte> encodedPositionMessage = new List <byte>(); List <byte> encodedTextMessage = new List <byte>(); //Now sit in an infinite loop of sending messages, roughly every 50ms while (!_shouldExit) { //This shouldn't fail, but if it does it will pick up where it left off try { //Start stopwatch timeElapsed = 0; watch.Reset(); watch.Start(); //Clear stuff Array.Clear(positionBytes, 0, 16); encodedPositionMessage.Clear(); encodedTextMessage.Clear(); //If player controller isn't created, wait if (playerController == null) { Thread.Sleep(_targetTimeBetweenTicks); continue; } //Do stuff //First get position info int sceneIndex = 0; lock (levelLock) { sceneIndex = NetworkManager.GetLevelIndex(levelName); } //Create position array numBuf = BitConverter.GetBytes(sceneIndex); if (BitConverter.IsLittleEndian) { Array.Reverse(numBuf); } Array.Copy(numBuf, 0, positionBytes, 0, 4); numBuf = BitConverter.GetBytes(xCoord); if (BitConverter.IsLittleEndian) { Array.Reverse(numBuf); } Array.Copy(numBuf, 0, positionBytes, 4, 4); numBuf = BitConverter.GetBytes(yCoord); if (BitConverter.IsLittleEndian) { Array.Reverse(numBuf); } Array.Copy(numBuf, 0, positionBytes, 8, 4); //Send position encodedPositionMessage.AddRange(_uniqueIdBytes); encodedPositionMessage.AddRange(Encode(positionBytes, 0)); byte[] epm = encodedPositionMessage.ToArray(); _udpSocket.Send(epm); _posSendCtr++; //Debug.Log("Sent UDP pos update " + _posSendCtr + ", bytes: " + epm.Length); //Get and send text, if there is any text = playerController.GetTextMessage(); if (!string.IsNullOrEmpty(text)) { encodedTextMessage.AddRange(_uniqueIdBytes); encodedTextMessage.AddRange(Encode(_encoder.GetBytes(text), 1)); byte[] etm = encodedTextMessage.ToArray(); _udpSocket.Send(etm); _txtSendCtr++; //Debug.Log("Sent UDP txt update " + _txtSendCtr); } } catch (Exception) { } //Stop stopwatch and sleep until ready for next tick watch.Stop(); timeElapsed = watch.ElapsedMilliseconds; if (timeElapsed < _targetTimeBetweenTicks) { //Debug.Log("Sleeping for " + (_targetTimeBetweenTicks - timeElapsed) + "ms"); Thread.Sleep((int)(_targetTimeBetweenTicks - timeElapsed)); } } }
protected void OnDataRecived(WebSocketSharp.MessageEventArgs e, string id) { string datasocketId = ToDataSocketID(id); TotalMessageRecivedEvents++; MemoryStream ms = new MemoryStream(e.RawData); WebsocketPipeMessageInfo[] msgs; System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); try { msgs = DataSocket.ReadMessages(ms).ToArray(); } catch (Exception ex) { string msg = "Error while reading messages from data socket: " + ex.Message; WriteLogMessage(id, msg); throw new Exception(msg, ex); } watch.Stop(); WriteLogTimeMessage(id, "Read from datasocket", watch.Elapsed.TotalMilliseconds); ms.Close(); ms.Dispose(); ms = null; watch.Reset(); watch.Start(); int bytecount = 0; MessageEventArgs[] mes = msgs.Select(msg => { bytecount = bytecount + msg.Data.Length; TMessage o; try { o = Serializer.FromBytes(msg.Data);; } catch (Exception ex) { var str = "Error desrializing message. " + ex.Message; WriteLogMessage(id, str); throw new Exception(str, ex); } return(new MessageEventArgs(o, msg.NeedsResponse, id)); }).ToArray(); WriteLogTimeMessage(id, "Deserialzed " + msgs.Length + " messages with " + bytecount + " [bytes] ", watch.Elapsed.TotalMilliseconds); watch.Stop(); watch.Reset(); watch.Start(); foreach (var me in mes) { if (TriggerWaitHandle(datasocketId, me.Message)) // this message is a response. { continue; } OnMessage(me); } watch.Stop(); WriteLogTimeMessage(id, "Handled evnets for " + msgs.Length + " messages", watch.Elapsed.TotalMilliseconds); }
IEnumerator total() { Debug.Log("now play" + totalnumber + "th time"); cross1.SetActive(true); cross2.SetActive(true); yield return(new WaitForSeconds(1F)); cross1.SetActive(false); cross2.SetActive(false); sw.Start(); now = sw.ElapsedMilliseconds; prints = now - before; before = now; debugtest += prints; //Debug.Log("start :" + prints + " real : " + sw.ElapsedMilliseconds); network.SendMessage("Send", prints + "#x#"); answer = answersheet[totalnumber]; switch (answer) { case 1: rend1.sharedMaterial = materials_on[0]; break; case 2: rend2.sharedMaterial = materials_on[1]; break; case 3: rend3.sharedMaterial = materials_on[2]; break; case 4: rend4.sharedMaterial = materials_on[3]; break; } yield return(new WaitForSeconds(0.5F)); now = sw.ElapsedMilliseconds; prints = now - before; before = now; debugtest += prints; //Debug.Log("answer :" + prints + " real : " + sw.ElapsedMilliseconds); Debug.Log("answer = " + answer); switch (answer) { case 1: if (training) { network.SendMessage("Send", prints + "#a#"); } break; case 2: if (training) { network.SendMessage("Send", prints + "#b#"); } break; case 3: if (training) { network.SendMessage("Send", prints + "#c#"); } break; case 4: if (training) { network.SendMessage("Send", prints + "#d#"); } break; } yield return(new WaitForSeconds(0.5F)); network.SendMessage("Send", "1#&1#2#&2#3#&2#4#&2#"); yield return(new WaitForSeconds(1F)); switch (answer) { case 1: rend1.sharedMaterial = materials_off[0]; break; case 2: rend2.sharedMaterial = materials_off[1]; break; case 3: rend3.sharedMaterial = materials_off[2]; break; case 4: rend4.sharedMaterial = materials_off[3]; break; } now = sw.ElapsedMilliseconds; prints = now - before; // 지연시간 측정 before = now; debugtest += prints; //Debug.Log("ready :" + prints + " real : " + sw.ElapsedMilliseconds); network.SendMessage("Send", prints + "#y#"); yield return(new WaitForSeconds(0.5F)); for (int i = 0; i < repeatnumber * 4; i++) // 깜빡임 { yield return(StartCoroutine(on())); } yield return(new WaitForSeconds(1F)); now = sw.ElapsedMilliseconds; prints = now - before; before = now; debugtest += prints; //Debug.Log("end :" + prints + " real : " + sw.ElapsedMilliseconds + " testing : " + debugtest); //테스트용 디버그 코드 network.SendMessage("Send", prints + "#z#"); yield return(new WaitForSeconds(1F)); end = true; now = 0; prints = 0; before = 0; debugtest = 0; sw.Stop(); sw.Reset(); }
public void DoReset() { iExcuteCount = 0; pStopWatch.Stop(); pStopWatch.Reset(); }