My main problem is that I don't know how to search what I'm looking for in google,because I get different results(probably its not count-down timer).
I want to calculate how much time a function takes to be executed.The instructions take a long time in seconds to be executed(seconds,not miliseconds).
How to do it in C#/NET,example?
You want to use the StopWatch.
See this question for more detail.
Is DateTime.Now the best way to measure a function's performance?
If you are looking to find bottlenecks in you application you can check out the CLR Profiler as a starting point.
Related
Forgive me for this question, but I can't seem to find a good source of when to use which. Would be happy if you can explain it in simple terms.
Furthermore, I am facing this dilemma:
See, I am coding a simple application. I want it to show the elapsed time (hh:mm:ss format or something). But also, to be able to "speed up" or "slow down" its time intervals (i.e. speed up so that a minute in real time equals an hour in the app).
For example, in Youtube videos (* let's not consider the fact that we can jump to specific parts of the vid *), we see the actual time spent in watching that video on the bottom left corner of the screen, but through navigating in the options menu, we are able to speed the video up or down.
And we can actually see that the time gets updated in a manner that agrees with the speed factor (like, if you choose twice the speed, the timer below gets updated twice faster than normal), and you can change this speed rate whenever you want.
This is what I'm kinda after. Something like how Youtube videos measure the time elapsed and the fact that they can change the time intervals. So, which of the two do you think I should choose? Timer or StopWatch?
I'm just coding a Windows Form Application, by the way. I'm simulating something and I want the user to be able to speed up whenever he or she wishes to. Simple as this may be, I wish to implement a proper approach.
As far as I know the main differences are:
Timer
Timer is just a simple scheduler that runs some operation/method once in a while
It executes method in a separate thread. This prevents blocking of the main thread
Timer is good when we need to execute some task in certain time interval without blocking anything.
Stopwatch
Stopwatch by default runs on the same thread
It counts time and returns TimeSpan struct that can be useful in case when we need some additional information
Stopwatch is good when we need to watch the time and get some additional information about how much elapsed processor ticks does the method take etc.
This has already been covered in a number of other questions including
here. Basically, you can either have Stopwatch with a Speed factor then the result is your "elapsed time". A more complicated approach is to implement Timer and changing the Interval property.
I am working on application that is testing human reaction time and I want it to be able to count the difference between reaction of one person and reaction of the other person. I tried to use timers but those standard timers in C# are not very effective and not really accurate, they can't count ~1ms difference, not even 5ms difference is accurate enough. Is there any way I could recognize the difference quite exactly? I could not really find something but I think that I could maybe take time of first reaction and then time of second reaction and get the difference but I did not manage to get exact time, is there any way to do that or should I use multimedia timer instead?
(I am looking for simple solution..)
You need to use the System.Diagnostics.Stopwatch class. Stopwatch will provide you with elapsed milliseconds, an elapsed TimeSpan, or elapsed ticks (each tick represents 100ns).
In my initialization method I call some other methods, manipulate some variables and iterate over some lists. Now I noticed that the loading method takes a little bit long (approximately 2 minutes).
But the problem is, I'm not quite sure which part of the method is consuming this much time. So I'd like to measure it so that I can work on this part that has the highest potential to reduce time.
But what is a good approach to measure that?
If you don't want to use a profiler such as the Ants performance profiler, you can use the Stopwatch to measure how long it took some code to run.
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
// Code to time
stopWatch.Stop();
TimeSpan ts = stopWatch.Elapsed;
This, of course changes your code and requires you to make these amendments in every point you want to measure.
I would recommend going with one of the many good profilers out there (I am certain other answers will point out some good ones).
The dotTrace Performance Profiler 4.0 provides line-by-line profiling. That's what you need.
I'm not quite sure which part of the
method is consuming this much time. So
I'd like to measure it
Things that take much longer than they should are very easy to find.
For example, if it's taking 10 times longer than it should, that means 90% of the time it is doing something not needed. So, if you run it under the IDE and pause it, the chance you will catch it in the act is 90%.
Just look at the call stack, because you know the problem is somewhere on it.
If you're not sure you've caught it, try it several times. The problem will appear on multiple samples.
Typical things I've found in .net app startup:
Looking up resources such as international strings, needlessly.
Walking notification trees in data structures, to a needless extent.
What you find will probably be different, but you will find it.
This is a low-tech but effective method. It works whether the time is spent in CPU or in I/O. It does not measure the problem very precisely, but it does locate it very precisely.
(Check the last paragraph of this post.)
I'm writing an application for a touch table using WPF and C#. (And, I'm not terribly familiar with WPF. At all.) We suspect we're not getting the framerate we're "requesting" from the API so I'm trying to write my own FPS calculator. I'm aware of the math to calculate it based on the internal clock, I just don't know how to access a timer within the Windows/WPF API.
What library/commands do I need to get access to a timer?
Although you could use a DispatcherTimer (which marshalls its ticks onto the ui thread, causing relativity problems), or a System.Threading.Timer (which might throw an exception if you try to touch any UI controls), i'd recommend you just use the WPF profiling tools :)
I think you're looking for the StopWatch. Just initialize it and reset it with each start of your iteration. At the end of an iteration, do your calculation.
First of all, are you aware that Microsoft provides a free diagnostic tool that will tell you the frame rate at which WPF is updating the screen? I guess if you're not convinced you're getting the framerate you're asking for, then perhaps you might not trust it, but I've found it to be a reliable tool. It's called Perforator, and it's part of the WPF Performance Suite, which you can get by following the instructions here: http://msdn.microsoft.com/library/aa969767
That's probably simpler than writing your own.
Also, how exactly are you "requesting" a frame rate? What API are you using? Are you using the Timeline's DesiredFrameRate property? If so, this is more commonly used to reduce the frame rate than increase it. (The docs also talk about increasing the frame rate to avoid tearing, but that doesn't really make sense - tearing is caused by presenting frames out of sync with the monitor, and isn't an artifact of slow frame rates. In any case, on Vista or Windows 7, you won't get tearing with the DWM enabled.) It's only a hint, and WPF does not promise to match the suggested frame rate.
As for the measurement technique, there are a number of ways you could go. If you're just trying to work out whether the frame rate is in the right ballpark, you could just increment a counter once per frame (which you'd typically do in an event handler for CompositionTarget.Rendering), and set up a DispatcherTimer to fire once a second, and have it show the value in the UI, and then reset the counter. It'll be somewhat rough and ready as DispatcherTimer isn't totally accurate, but it'll show you whether you've got 15fps when you were expecting 30fps, for example.
If you're trying to get a more precise view (e.g., you want to try to work out whether frames are being rendered constantly, or if you seem to be getting lost frames from time to time), then that gets a bit more complex. But I'll wait to see if Perforator does the trick for you before making more suggestions.
You want to either wrap the win32 timing calls you'd normally call (such as QueryPerformanceCounter), by using p/Invoke, or use something in .NET that already wraps them.
You could use DateTime.Ticks, but it's probably not high enough resolution. The Stopwatch class uses QueryPerformanceCounter under the covers.
If you want something that's reusable on a lot of systems, rather than a simple diagnostic, be warned about processor related issues w/ QPC and Stopwatch. See this question: Can the .NET Stopwatch class be THIS terrible?
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.
I've just written an article that explains how a test setup must be done to get an high accuracy (better than 0.1ms) out of the stopwatch. I Think it should explain everything.
http://www.codeproject.com/KB/testing/stopwatch-measure-precise.aspx
The System.Diagnostics.Stopwatch class does accurately measure time elapsed, but the way that the ElapsedTicks method works has led some people to the conclusion that it is not accurate, when they really just have a logic error in their code.
The reason that some developers think that the Stopwatch is not accurate is that the ElapsedTicks from the Stopwatch DO NOT EQUATE to the Ticks in a DateTime.
The problem arises when the application code uses the ElapsedTicks to create a new DateTime.
var watch = new Stopwatch();
watch.Start();
... (perform a set of operations)
watch.Stop();
var wrongDate = new DateTime(watch.ElapsedTicks); // This is the WRONG value.
If necessary, the stopwatch duration can be converted to a DateTime in the following way:
// This converts stopwatch ticks into DateTime ticks.
// First convert to TimeSpan, then convert to DateTime
var rightDate = new DateTime(watch.Elapsed.Ticks);
Here is an article that explains the problem in more detail:
http://geekswithblogs.net/BlackRabbitCoder/archive/2012/01/12/c.net-little-pitfalls-stopwatch-ticks-are-not-timespan-ticks.aspx
Note that the content is no longer available at the original link. Here is a reference to the archived content from the Wayback Machine:
https://web.archive.org/web/20190104073827/http://geekswithblogs.net:80/BlackRabbitCoder/archive/2012/01/12/c.net-little-pitfalls-stopwatch-ticks-are-not-timespan-ticks.aspx
Stopwatch class return different values under different configuration as Frequency depends on the installed hardware & operating system.
Using stopwatch class we can have only the rough estimation of execution time. And for each execution it returns different value so we have to take average of different execution.
More Info : http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
First, exact is of course not a possible or meaningful concept when talking about time or space, since no empyrical measurement of a physical magnitude can ever pretend to be exact.
Second, David Bolton's blog article may be useful. I'm quoting:
If this was timed with the high resolution counter then it will be accurate to microseconds. It is actually accurate to nanoseconds (10-9 seconds, ie a billionth of a second) but there is so much other stuff going on that nanosecond accuracy is really a bit pointless. When doing timing or benchmarking of code, you should do a number of runs and take the average time- because of other processes running under Windows, how much swapping to disk is occurring etc, the values between two runs may vary.
MSDN has some examples of the stopwatch. They also have it showing how accurate it is within Nanoseconds. Hope this helps!
Why you don't profile your code instead of focusing on micro-benchmarks?
There are some good Open Source profilers like:
NProf
Prof-It for C#
NProfiler
ProfileSharp
In addition to seconding the advice of HUAGHAGUAH above, I'd add that you should be VERY skeptical of micro-benchmarks in general. While close-focused performance testing has a legitimate place, it's very easy to tweak an unimportant detail. So write and verify code that is designed for readability and clarity, then profile it to find out where the hot spots are (or whether there are any worth worrying about), and then tune (only) those portions.
I recall working with a programmer who micro-optimized a bit of code that executed while the system waited for human input. The time savings absolutely disappeared in the between-keystroke lag!
If you want more precise timings. Take a look at the QueryPerformanceCounter. MSDN link for QueryPerformanceCounter. A neat implementation is given here. The example loads coredll.dll for CE, for Windows you should load the Kernel32.dll as stated in the MSDN documentation.