Search Results

Search found 148 results on 6 pages for 'stopwatch'.

Page 1/6 | 1 2 3 4 5 6  | Next Page >

  • Using the StopWatch class to calculate the execution time of a block of code

    - by vik20000in
      Many of the times while doing the performance tuning of some, class, webpage, component, control etc. we first measure the current time taken in the execution of that code. This helps in understanding the location in code which is actually causing the performance issue and also help in measuring the amount of improvement by making the changes. This measurement is very important as it helps us understand the problem in code, Helps us to write better code next time (as we have already learnt what kind of improvement can be made with different code) . Normally developers create 2 objects of the DateTime class. The exact time is collected before and after the code where the performance needs to be measured.  Next the difference between the two objects is used to know about the time spent in the code that is measured. Below is an example of the sample code.             DateTime dt1, dt2;             dt1 = DateTime.Now;             for (int i = 0; i < 1000000; i++)             {                 string str = "string";             }             dt2 = DateTime.Now;             TimeSpan ts = dt2.Subtract(dt1);             Console.WriteLine("Time Spent : " + ts.TotalMilliseconds.ToString());   The above code works great. But the dot net framework also provides for another way to capture the time spent on the code without doing much effort (creating 2 datetime object, timespan object etc..). We can use the inbuilt StopWatch class to get the exact time spent. Below is an example of the same work with the help of the StopWatch class.             Stopwatch sw = Stopwatch.StartNew();             for (int i = 0; i < 1000000; i++)             {                 string str = "string";             }             sw.Stop();             Console.WriteLine("Time Spent : " +sw.Elapsed.TotalMilliseconds.ToString());   [Note the StopWatch class resides in the System.Diagnostics namespace] If you use the StopWatch class the time taken for measuring the performance is much better, with very little effort. Vikram

    Read the article

  • How can i use Stopwatch [ apache ] to calculate the time taken by a method?

    - by Rakesh Juyal
    I am using StopWatch [ apache ] to get the time taken by my method. The approach i am following is StopWatch stopWatch = new StopWatch(); stopWatch.start(); myMethod(); stopWatch.stop(); logger.info( "Time taken by myMethod: " + stopWatch.getTime() + " millisecs"); stopWatch.reset(); stopWatch.start(); anotherMethod(); stopWatch.stop(); logger.info( "Time taken by anotherMethod: " + stopWatch.getTime() + " millisecs"); Thats the only thing i know about StopWatch :). How/when to use split(), unsplit(), getSplitTime(),suspend()... ?

    Read the article

  • Blackberry stopwatch implementation

    - by Michaela
    I'm trying to write a blackberry app that is basically a stopwatch, and displays lap times. First, I'm not sure I'm implementing the stopwatch functionality in the most optimal way. I have a LabelField (_myLabel) that displays the 'clock' - starting at 00:00. Then you hit the start button and every second the _myLabel field gets updated with how many seconds have past since the last update (should only ever increment by 1, but sometimes there is a delay and it will skip a number). I just can't think of a different way to do it - and I am new to GUI development and threads so I guess that's why. EDIT: Here is what calls the stopwatch: _timer = new Timer(); _timer.schedule(new MyTimerTask(), 250, 250); And here is the TimerTask: class MyTimerTask extends TimerTask { long currentTime; long startTime = System.currentTimeMillis(); public void run() { synchronized (Application.getEventLock()) { currentTime = System.currentTimeMillis(); long diff = currentTime - startTime; long min = diff / 60000; long sec = (diff % 60000) / 1000; String minStr = new Long(min).toString(); String secStr = new Long(sec).toString(); if (min < 10) minStr = "0" + minStr; if (sec < 10) secStr = "0" + secStr; _myLabel.setText(minStr + ":" + secStr); timerDisplay.deleteAll(); timerDisplay.add(_timerLabel); } } } Anyway when you stop the stopwatch it updates a historical table of lap time data. When this list gets long, the timer starts to degrade. If you try to scroll, then it gets really bad. Is there a better way to implement my stopwatch?

    Read the article

  • stopwatch accuracy

    - by oo
    How accurate is System.Diagnostics.Stopwatch? I am trying to do some metrics for different code paths and I need it to be exact. Should I be using stopwatch or is there another solution that is more accurate. I have been told that sometimes stopwatch gives incorrect information.

    Read the article

  • Is Stopwatch really broken?

    - by Jakub Šturc
    At MSDN page for Stopwatch class I discovered link to interesting article which makes following statement about Stopwatch: However there are some serious issues: This can be unreliable on a PC with multiple processors. Due to a bug in the BIOS, Start() and Stop() must be executed on the same processor to get a correct result. This is unreliable on processors that do not have a constant clock speed (most processors can reduce the clock speed to conserve energy). This is explained in detail here. I am little confused. I've seen tons of examples of using Stopwatch and nobody mention this drawbacks. How serious is this? Should I avoid using Stopwatch?

    Read the article

  • OpenNETCF.Stopwatch -> only ticks changing, not Elapsed

    - by pithyless
    I've been trying to track down a bug I thought was thread-related, but I think instead there is an issue with the way I am using OpenNETCF's Stopwatch. I am using OpenNETCF.IoC in my application, but for the sake of simplicity I moved the following code directly into a view: public partial class WorkoutView : SmartPart { ... private Stopwatch stopwatch; public WorkoutView() { ... stopwatch = new Stopwatch(); stopwatch.Reset(); stopwatch.Start(); WorkoutDisplayTimer = new Timer(); WorkoutDisplayTimer.Interval = 500; WorkoutDisplayTimer.Tick += new EventHandler(WorkoutDisplayTimer_Tick); WorkoutDisplayTimer.Enabled = true; } void WorkoutDisplayTimer_Tick(object sender, EventArgs e) { ... stopwatch.Stop(); lbl.Text = stopwatch.ElapsedTicks.ToString() + "NOT WORKING: " + stopwatch.Elapsed.ToString(); stopwatch.Start(); } ... } Long story short, looking at stopwatch in the debugger, the only values that ever get updated are ElapsedTicks, mElapsed, mStartPerfCount. Everything else is always zero. Is this expected behavior? Do I need to call an additional method to have the stopwatch calculate the Elapsed struct? (Note: stopwatch.ElapsedMilliseconds is also zero)

    Read the article

  • Can Stopwatch be used in production code?

    - by Adrian
    Hi, I need an accurate timer, and DateTime.Now seems not accurate enough. From the descriptions I read, System.Diagnostics.Stopwatch seems to be exactly what I want. But I have a phobia. I'm nervous about using anything from System.Diagnostics in actual production code. (I use it extensively for debugging with Asserts and PrintLns etc, but never yet for production stuff.) I'm not merely trying to use a timer to benchmark my functions - my app needs an actual timer. I've read on another forum that System.Diagnostics.StopWatch is only for benchmarking, and shouldn't be used in retail code, though there was no reason given. Is this correct, or am I (and whoever posted that advice) being too closed minded about System.Diagnostics? ie, is it ok to use System.Diagnostics.Stopwatch in production code? Thanks Adrian

    Read the article

  • Best Practise for Stopwatch in multi processors machine?

    - by Ahmed Said
    I found a good question for measuring function performance, and the answers recommend to use Stopwatch as follows Stopwatch sw = new Stopwatch(); sw.Start(); //DoWork sw.Stop(); //take sw.Elapsed But is this valid if you are running under multi processors machine? the thread can be switched to another processor, can it? Also the same thing should be in Enviroment.TickCount. If the answer is yes should I wrap my code inside BeginThreadAffinity as follows Thread.BeginThreadAffinity(); Stopwatch sw = new Stopwatch(); sw.Start(); //DoWork sw.Stop(); //take sw.Elapsed Thread.EndThreadAffinity(); P.S The switching can occur over the thread level not only the processor level, for example if the function is running in another thread so the system can switch it to another processor, if that happens, will the Stopwatch be valid after this switching? I am not using Stopwatch for perfromance measurement only but also to simulate timer function using Thread.Sleep (to prevent call overlapping)

    Read the article

  • How would I go about implementing a stopwatch with different speeds?

    - by James
    Ideally I would like to have something similar to the Stopwatch class but with an extra property called Speed which would determine how quickly the timer changes minutes. I am not quite sure how I would go about implementing this. Edit Since people don't quite seem to understand why I want to do this. Consider playing a soccer game, or any sport game. The halfs are measured in minutes, but the time-frame in which the game is played is significantly lower i.e. a 45 minute half is played in about 2.5 minutes.

    Read the article

  • Why does the Ternary\Conditional operator seem significantly faster

    - by Jodrell
    Following on from this question, which I have partially answered. I compile this console app in x64 Release Mode, with optimizations on, and run it from the command line without a debugger attached. using System; using System.Diagnostics; class Program { static void Main() { var stopwatch = new Stopwatch(); var ternary = Looper(10, Ternary); var normal = Looper(10, Normal); if (ternary != normal) { throw new Exception(); } stopwatch.Start(); ternary = Looper(10000000, Ternary); stopWatch.Stop(); Console.WriteLine( "Ternary took {0}ms", stopwatch.ElapsedMilliseconds); stopwatch.Start(); normal = Looper(10000000, Normal); stopWatch.Stop(); Console.WriteLine( "Normal took {0}ms", stopwatch.ElapsedMilliseconds); if (ternary != normal) { throw new Exception(); } Console.ReadKey(); } static int Looper(int iterations, Func<bool, int, int> operation) { var result = 0; for (int i = 0; i < iterations; i++) { var condition = result % 11 == 4; var value = ((i * 11) / 3) % 5; result = operation(condition, value); } return result; } static int Ternary(bool condition, in value) { return value + (condition ? 2 : 1); } static int Normal(int iterations) { if (condition) { return = 2 + value; } return = 1 + value; } } I don't get any exceptions and the output to the console is somthing close to, Ternary took 107ms Normal took 230ms When I break down the CIL for the two logical functions I get this, ... Ternary ... { : ldarg.1 // push second arg : ldarg.0 // push first arg : brtrue.s T // if first arg is true jump to T : ldc.i4.1 // push int32(1) : br.s F // jump to F T: ldc.i4.2 // push int32(2) F: add // add either 1 or 2 to second arg : ret // return result } ... Normal ... { : ldarg.0 // push first arg : brfalse.s F // if first arg is false jump to F : ldc.i4.2 // push int32(2) : ldarg.1 // push second arg : add // add second arg to 2 : ret // return result F: ldc.i4.1 // push int32(1) : ldarg.1 // push second arg : add // add second arg to 1 : ret // return result } Whilst the Ternary CIL is a little shorter, it seems to me that the execution path through the CIL for either function takes 3 loads and 1 or 2 jumps and a return. Why does the Ternary function appear to be twice as fast. I underdtand that, in practice, they are both very quick and indeed, quich enough but, I would like to understand the discrepancy.

    Read the article

  • Stop a stopwatch

    - by James Morgan
    I have the following code in a JPanel class which is added to a another class (JFrame). What I'm trying to implement is some sort of a stopwatch program. startBtn.addActionListener(new startListener()); class startListener implements ActionListener { public void actionPerformed(ActionEvent e) { Timer time = new Timer(); time.scheduleAtFixedRate(new Stopwatch(), 1000, 1000); } } This is another class which basically the task. public class Stopwatch extends TimerTask { private final double start = System.currentTimeMillis(); public void run() { double curr = System.currentTimeMillis(); System.out.println((curr - start) / 1000); } } The timer works fine and this is definitely far from complete but I'm not sure how to code the stop button which should stop the timer. Any advice on this? BTW I'm using java.util.timer

    Read the article

  • Converting a stopwatch time to milliseconds (regex)

    - by Nick
    I'm trying to figure out the best way to convert a string containing a time to an integer number of milliseconds. I'm using a suboptimal way using a bunch of preg_match()'s and some array handling, but I was wondering if there was an elegant way. Here are some example stopwatch times (some wouldn't actually be seen on a stopwatch but need to be converted anyway): 3:34:05.81 34:05 5 (just 5 seconds) 89 (89 seconds) 76:05 (76 minutes, 5 seconds) Millseconds will not extend past 2 decimal places. You can give me an example using either PHP or Javascript regex functions. Thanks!

    Read the article

  • How do you link a time stamp to a cell using a userform button control? [migrated]

    - by Chad Cochrane
    Hello fellow VB Developers/Users/Hobbyists/What-Have-You! I have a user form that has two buttons: 1. Start 2. Stop When I press start, I would like it to record the current time with this format: (dd/mm/yy hh:nn:ss:) in a specific column. Then when I press the Stop Button I would like it to record the time again in the cell next to it. Then if I press start Again I would like it to record below the first cells current record. Basically I am building a timer to record data to see how long certain tasks take. I will post the excel file and provide more information were necessary. Thanks for any help provided. CURRENT CODE Public runTimer As Double Public startTime As Date Dim counter As Date Sub setStart() counter = 0 startTime = Now runTimer = Now + TimeSerial(0, 0, 1) Application.OnTime runTimer, "setStart", , True Set myTime = Sheet4.Range("F1") Set timeRng = Sheet4.Range("C8:C100") i = WorksheetFunction.CountA(timeRng) i = i + 1 Cells(i, "C") = myTime Sheet4.Cells(i, "C").NumberFormat = "yyyy/mm/dd HH:mm:ss" If i >= 2 Then Cells(i, "D8") = Cells(i, "C8") - Cells(i - 1, "C8") Sheet4.Cells(i, "C").NumberFormat = "yyyy/mm/dd HH:mm:ss" End If Application.EnableEvents = False End Sub Sub setStop() Application.OnTime runTimer, "setStop", , True Set myTime = Sheet4.Range("F1") Set timeRng = Sheet4.Range("D8:D100") i = WorksheetFunction.CountA(timeRng) i = i + 1 Application.EnableEvents = False Cells(i, "D") = myTime Sheet4.Cells(i, "D").NumberFormat = "yyyy/mm/dd HH:mm:ss" End Sub

    Read the article

  • Timer applications running under lock on Windows Phone 7

    - by cpedros
    Under the current Windows Phone 7 Application Certification Requirements (pdf) applications running under lock must "stop any ... active timers" (section 6.3.1). However looking out on Marketplace there are a number of timer/stopwatch apps claiming to run under lock and also allow lock to be disabled in their settings. How are these apps certified or is there some loosening on the restrictions by Microsoft if the app allows the user to make that decision? Also some of these apps also suggest they continue even when the app is exited or when the device off. Is it the case that they are not truly running under these circumstances, i.e. the timers either start where they left off when reactivated, or perhaps use the OS time to work out the time elapsed between tombstoning and reactivation? In these circumstance I also presume it is not possible for the app to notify the user when the timer completes?

    Read the article

  • C# Confusing Results from Performance Test

    - by aip.cd.aish
    I am currently working on an image processing application. The application captures images from a webcam and then does some processing on it. The app needs to be real time responsive (ideally < 50ms to process each request). I have been doing some timing tests on the code I have and I found something very interesting (see below). clearLog(); log("Log cleared"); camera.QueryFrame(); camera.QueryFrame(); log("Camera buffer cleared"); Sensor s = t.val; log("Sx: " + S.X + " Sy: " + S.Y); Image<Bgr, Byte> cameraImage = camera.QueryFrame(); log("Camera output acuired for processing"); Each time the log is called the time since the beginning of the processing is displayed. Here is my log output: [3 ms]Log cleared [41 ms]Camera buffer cleared [41 ms]Sx: 589 Sy: 414 [112 ms]Camera output acuired for processing The timings are computed using a StopWatch from System.Diagonostics. QUESTION 1 I find this slightly interesting, since when the same method is called twice it executes in ~40ms and when it is called once the next time it took longer (~70ms). Assigning the value can't really be taking that long right? QUESTION 2 Also the timing for each step recorded above varies from time to time. The values for some steps are sometimes as low as 0ms and sometimes as high as 100ms. Though most of the numbers seem to be relatively consistent. I guess this may be because the CPU was used by some other process in the mean time? (If this is for some other reason, please let me know) Is there some way to ensure that when this function runs, it gets the highest priority? So that the speed test results will be consistently low (in terms of time). EDIT I change the code to remove the two blank query frames from above, so the code is now: clearLog(); log("Log cleared"); Sensor s = t.val; log("Sx: " + S.X + " Sy: " + S.Y); Image<Bgr, Byte> cameraImage = camera.QueryFrame(); log("Camera output acuired for processing"); The timing results are now: [2 ms]Log cleared [3 ms]Sx: 589 Sy: 414 [5 ms]Camera output acuired for processing The next steps now take longer (sometimes, the next step jumps to after 20-30ms, while the next step was previously almost instantaneous). I am guessing this is due to the CPU scheduling. Is there someway I can ensure the CPU does not get scheduled to do something else while it is running through this code?

    Read the article

  • Parallel LINQ - PLINQ

    - by nmarun
    Turns out now with .net 4.0 we can run a query like a multi-threaded application. Say you want to query a collection of objects and return only those that meet certain conditions. Until now, we basically had one ‘control’ that iterated over all the objects in the collection, checked the condition on each object and returned if it passed. We obviously agree that if we can ‘break’ this task into smaller ones, assign each task to a different ‘control’ and ask all the controls to do their job - in-parallel, the time taken the finish the entire task will be much lower. Welcome to PLINQ. Let’s take some examples. I have the following method that uses our good ol’ LINQ. 1: private static void Linq(int lowerLimit, int upperLimit) 2: { 3: // populate an array with int values from lowerLimit to the upperLimit 4: var source = Enumerable.Range(lowerLimit, upperLimit); 5:  6: // Start a timer 7: Stopwatch stopwatch = new Stopwatch(); 8: stopwatch.Start(); 9:  10: // set the expectation => build the expression tree 11: var evenNumbers =   from num in source 12: where IsDivisibleBy(num, 2) 13: select num; 14: 15: // iterate over and print the returned items 16: foreach (var number in evenNumbers) 17: { 18: Console.WriteLine(string.Format("** {0}", number)); 19: } 20:  21: stopwatch.Stop(); 22:  23: // check the metrics 24: Console.WriteLine(String.Format("Elapsed {0}ms", stopwatch.ElapsedMilliseconds)); 25: } I’ve added comments for the major steps, but the only thing I want to talk about here is the IsDivisibleBy() method. I know I could have just included the logic directly in the where clause. I called a method to add ‘delay’ to the execution of the query - to simulate a loooooooooong operation (will be easier to compare the results). 1: private static bool IsDivisibleBy(int number, int divisor) 2: { 3: // iterate over some database query 4: // to add time to the execution of this method; 5: // the TableB has around 10 records 6: for (int i = 0; i < 10; i++) 7: { 8: DataClasses1DataContext dataContext = new DataClasses1DataContext(); 9: var query = from b in dataContext.TableBs select b; 10: 11: foreach (var row in query) 12: { 13: // Do NOTHING (wish my job was like this) 14: } 15: } 16:  17: return number % divisor == 0; 18: } Now, let’s look at how to modify this to PLINQ. 1: private static void Plinq(int lowerLimit, int upperLimit) 2: { 3: // populate an array with int values from lowerLimit to the upperLimit 4: var source = Enumerable.Range(lowerLimit, upperLimit); 5:  6: // Start a timer 7: Stopwatch stopwatch = new Stopwatch(); 8: stopwatch.Start(); 9:  10: // set the expectation => build the expression tree 11: var evenNumbers = from num in source.AsParallel() 12: where IsDivisibleBy(num, 2) 13: select num; 14:  15: // iterate over and print the returned items 16: foreach (var number in evenNumbers) 17: { 18: Console.WriteLine(string.Format("** {0}", number)); 19: } 20:  21: stopwatch.Stop(); 22:  23: // check the metrics 24: Console.WriteLine(String.Format("Elapsed {0}ms", stopwatch.ElapsedMilliseconds)); 25: } That’s it, this is now in PLINQ format. Oh and if you haven’t found the difference, look line 11 a little more closely. You’ll see an extension method ‘AsParallel()’ added to the ‘source’ variable. Couldn’t be more simpler right? So this is going to improve the performance for us. Let’s test it. So in my Main method of the Console application that I’m working on, I make a call to both. 1: static void Main(string[] args) 2: { 3: // set lower and upper limits 4: int lowerLimit = 1; 5: int upperLimit = 20; 6: // call the methods 7: Console.WriteLine("Calling Linq() method"); 8: Linq(lowerLimit, upperLimit); 9: 10: Console.WriteLine(); 11: Console.WriteLine("Calling Plinq() method"); 12: Plinq(lowerLimit, upperLimit); 13:  14: Console.ReadLine(); // just so I get enough time to read the output 15: } YMMV, but here are the results that I got:    It’s quite obvious from the above results that the Plinq() method is taking considerably less time than the Linq() version. I’m sure you’ve already noticed that the output of the Plinq() method is not in order. That’s because, each of the ‘control’s we sent to fetch the results, reported with values as and when they obtained them. This is something about parallel LINQ that one needs to remember – the collection cannot be guaranteed to be undisturbed. This could be counted as a negative about PLINQ (emphasize ‘could’). Nevertheless, if we want the collection to be sorted, we can use a SortedSet (.net 4.0) or build our own custom ‘sorter’. Either way we go, there’s a good chance we’ll end up with a better performance using PLINQ. And there’s another negative of PLINQ (depending on how you see it). This is regarding the CPU cycles. See the usage for Linq() method (used ResourceMonitor): I have dual CPU’s and see the height of the peak in the bottom two blocks and now compare to what happens when I run the Plinq() method. The difference is obvious. Higher usage, but for a shorter duration (width of the peak). Both these points make sense in both cases. Linq() runs for a longer time, but uses less resources whereas Plinq() runs for a shorter time and consumes more resources. Even after knowing all these, I’m still inclined towards PLINQ. PLINQ rocks! (no hard feelings LINQ)

    Read the article

  • C# performance analysis- how to count CPU cycles?

    - by Lirik
    Is this a valid way to do performance analysis? I want to get nanosecond accuracy and determine the performance of typecasting: class PerformanceTest { static double last = 0.0; static List<object> numericGenericData = new List<object>(); static List<double> numericTypedData = new List<double>(); static void Main(string[] args) { double totalWithCasting = 0.0; double totalWithoutCasting = 0.0; for (double d = 0.0; d < 1000000.0; ++d) { numericGenericData.Add(d); numericTypedData.Add(d); } Stopwatch stopwatch = new Stopwatch(); for (int i = 0; i < 10; ++i) { stopwatch.Start(); testWithTypecasting(); stopwatch.Stop(); totalWithCasting += stopwatch.ElapsedTicks; stopwatch.Start(); testWithoutTypeCasting(); stopwatch.Stop(); totalWithoutCasting += stopwatch.ElapsedTicks; } Console.WriteLine("Avg with typecasting = {0}", (totalWithCasting/10)); Console.WriteLine("Avg without typecasting = {0}", (totalWithoutCasting/10)); Console.ReadKey(); } static void testWithTypecasting() { foreach (object o in numericGenericData) { last = ((double)o*(double)o)/200; } } static void testWithoutTypeCasting() { foreach (double d in numericTypedData) { last = (d * d)/200; } } } The output is: Avg with typecasting = 468872.3 Avg without typecasting = 501157.9 I'm a little suspicious... it looks like there is nearly no impact on the performance. Is casting really that cheap?

    Read the article

  • Does "for" in .Net Framework 4.0 execute loops in parallel? Or why is the total not the sum of the p

    - by Shiraz Bhaiji
    I am writing code to performance test a web site. I have the following code: string url = "http://xxxxxx"; System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch(); System.Diagnostics.Stopwatch totalTime = new System.Diagnostics.Stopwatch(); totalTime.Start(); for (int i = 0; i < 10; i++) { stopwatch.Start(); WebRequest request = HttpWebRequest.Create(url); WebResponse webResponse = request.GetResponse(); webResponse.Close(); stopwatch.Stop(); textBox1.Text += "Time Taken " + i.ToString() + " = " + stopwatch.Elapsed.Milliseconds.ToString() + Environment.NewLine; stopwatch.Reset(); } totalTime.Stop(); textBox1.Text += "Total Time Taken = " + totalTime.Elapsed.Milliseconds.ToString() + Environment.NewLine; Which is giving the following result: Time Taken 0 = 88 Time Taken 1 = 161 Time Taken 2 = 218 Time Taken 3 = 417 Time Taken 4 = 236 Time Taken 5 = 217 Time Taken 6 = 217 Time Taken 7 = 218 Time Taken 8 = 409 Time Taken 9 = 48 Total Time Taken = 257 I had expected the total time to be the sum of the individual times. Can anybody see why it is not?

    Read the article

  • Why does ElapsedTicks X 10 000 not equal ElapsedMilliseconds for .Net's Stopwatch?

    - by uriDium
    I am trying to performance test some code. I am using a stopwatch. When I output the number of milliseconds it always tells me 0 so I thought that I would try the number of ticks. I am seeing that the number of ticks is about 20 000 to 30 000. Looking at the MSDN at TimeSpan.TicksPerMillisecond it says that is 10 000 ticks per millisecond. In that case why are the elapsed milliseconds on my stopwatch not appearing as 2 or 3? What am I missing? I have even outputed the result on the same line. This is what I get. Time taken: 26856 ticks, 0 ms And it is constant.

    Read the article

  • Stopwatch vs. using System.DateTime.Now for timing events

    - by Randy Minder
    I wanted to track the performance of a piece of my application so I initially stored the start time using System.DateTime.Now and the end time also using System.DateTime.Now. The difference between the two was how long my code took to execute. I noticed though that the difference didn't appear to be accurate. So I tried using a Stopwatch object. This turned out to be much, much more accurate. Can anyone tell me why Stopwatch would be more accurate than calculating the difference between a start and end time using System.DateTime.Now? Thanks.

    Read the article

  • Delay command execution over sockets

    - by David
    I've been trying to fix the game loop in a real time (tick delay) MUD. I realized using Thread.Sleep would seem clunky when the user spammed commands through their choice of client (Zmud, etc) e.g. east;south;southwest would wait three move ticks and then output everything from the past couple rooms. The game loop basically calls a Flush and Fill method for each socket during each tick (50ms) private void DoLoop() { Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); while (running) { // for each socket, flush and fill ConnectionMonitor.Update(); stopWatch.Stop(); WaitIfNeeded(stopWatch.ElapsedMilliseconds); stopWatch.Reset(); } } The Fill method fires the command events, but as mentioned before, they currently block using Thread.Sleep. I tried adding a "ready" flag to the state object that attempts to execute the command along with a queue of spammed commands, but it ends up executing one command and queuing up the rest i.e. each subsequent command executes something that got queued up that should've been executed before. I must be missing something about the timer. private readonly Queue<SpammedCommand> queuedCommands = new Queue<SpammedCommand>(); private bool ready = true; private void TryExecuteCommand(string input) { var commandContext = CommandContext.Create(input); var player = Server.Current.Database.Get<Player>(Session.Player.Key); var commandInfo = Server.Current.CommandLookup .FindCommand(commandContext.CommandName, player.IsAdmin); if (commandInfo != null) { if (!ready) { // queue command queuedCommands.Enqueue(new SpammedCommand() { Context = commandContext, Info = commandInfo }); return; } if (queuedCommands.Count > 0) { // queue the incoming command queuedCommands.Enqueue(new SpammedCommand() { Context = commandContext, Info = commandInfo, }); // dequeue and execute var command = queuedCommands.Dequeue(); command.Info.Command.Execute(Session, command.Context); setTimeout(command.Info.TickLength); return; } commandInfo.Command.Execute(Session, commandContext); setTimeout(commandInfo.TickLength); } else { Session.WriteLine("Command not recognized"); } } Finally, setTimeout was supposed to set the execution delay (TickLength) for that command, and makeReady just sets the ready flag on the state object to true. private void setTimeout(TickDelay tickDelay) { ready = false; var t = new System.Timers.Timer() { Interval = (long) tickDelay, AutoReset = false, }; t.Elapsed += makeReady; t.Start(); // fire this in tickDelay ms } // MAKE READYYYYY!!!! private void makeReady(object sender, System.Timers.ElapsedEventArgs e) { ready = true; } Am I missing something about the System.Timers.Timer created in setTimeout? How can I execute (and output) spammed commands per TickLength without using Thread.Sleep?

    Read the article

  • How accurately (in terms of time) does Windows play audio?

    - by MusiGenesis
    Let's say I play a stereo WAV file with 317,520,000 samples, which is theoretically 1 hour long. Assuming no interruptions of the playback, will the file finish playing in exactly one hour, or is there some occasional tiny variation in the playback speed such that it would be slightly more or slightly less (by some number of milliseconds) than one hour? I am trying to synchronize animation with audio, and I am using a System.Diagnostics.Stopwatch to keep the frames matching the audio. But if the playback speed of WAV audio in Windows can vary slightly over time, then the audio will drift out of sync with the Stopwatch-driven animation. Which leads to a second question: it appears that a Stopwatch - while highly granular and accurate for short durations - runs slightly fast. On my laptop, a Stopwatch run for exactly 24 hours (as measured by the computer's system time and a real stopwatch) shows an elapsed time of 24 hours plus about 5 seconds (not milliseconds). Is this a known problem with Stopwatch? (A related question would be "am I crazy?", but you can try it for yourself.) Given its usage as a diagnostics tool, I can see where a discrepancy like this would only show up when measuring long durations, for which most people would use something other than a Stopwatch. If I'm really lucky, then both Stopwatch and audio playback are driven by the same underlying mechanism, and thus will stay in sync with each other for days on end. Any chance this is true?

    Read the article

  • How to get timestamp of tick precision in .NET / C#?

    - by Hermann
    Up until now I used DateTime.Now for getting timestamps, but I noticed that if you print DateTime.Now in a loop you will see that it increments in descrete jumps of approx. 15 ms. But for certain scenarios in my application I need to get the most accurate timestamp possible, preferably with tick (=100 ns) precision. Any ideas? Update: Apparently, StopWatch / QueryPerformanceCounter is the way to go, but it can only be used to measure time, so I was thinking about calling DateTime.Now when the application starts up and then just have StopWatch run and then just add the elapsed time from StopWatch to the initial value returned from DateTime.Now. At least that should give me accurate relative timestamps, right? What do you think about that (hack)? NOTE: StopWatch.ElapsedTicks is different from StopWatch.Elapsed.Ticks! I used the former assuming 1 tick = 100 ns, but in this case 1 tick = 1 / StopWatch.Frequency. So to get ticks equivalent to DateTime use StopWatch.Elapsed.Ticks. I just learned this the hard way. NOTE 2: Using the StopWatch approach, I noticed it gets out of sync with the real time. After about 10 hours, it was ahead by 5 seconds. So I guess one would have to resync it every X or so where X could be 1 hour, 30 min, 15 min, etc. I am not sure what the optimal timespan for resyncing would be since every resync will change the offset which can be up to 20 ms.

    Read the article

1 2 3 4 5 6  | Next Page >