I know this question has been asked more than once, but I'm not sure if the results I'm having are right. The operation seems too fast, so I'd like to double check if that's really it.
I have a routine that splits a string into a List<byte[]>. I wanted to check the time it takes for the operation, so I modified the code to be like the following:
// Deserializes base64 received from POST service
var str = JsonConvert.DeserializeObject<JsonText>(body).text;
Stopwatch stopWatch = Stopwatch.StartNew();
// parseText is a routine that splits str into
// byte[] of maximum size 100 and puts them into
// a List<byte[]> that is then returned
commands = DummyClass.parseText(str);
stopWatch.Stop();
TimeSpan timespan = stopWatch.Elapsed;
Console.WriteLine(timespan.TotalMilliseconds.ToString("0.0###"));
...
I ran the routine using a 8000 character string and expected a couple miliseconds op time, but surprisingly the whole operation runs to at most 0.8ms which I expected to be a whole lot slower.
Am I reading the measurements wrong? Does 0.8 means 8ms? Did I do something wrong while measuring the time?
Thank you very much!
Instead of
TimeSpan timespan = stopWatch.Elapsed;
Console.WriteLine(timespan.TotalMilliseconds.ToString("0.0###"));
Why not try
Console.WriteLine("Elapsed time {0} ms",stopWatch.ElapsedMilliseconds);
You want milliseconds, you have them in stopwatch class directly - no need to visit string.format and timespan libraries.
I think that your operation runs much faster than 1 ms, to measure such small values use timer ticks:
stopWatch.ElapsedTicks
Related
In my c# program, my requirement is to calculate a timespan for business logic execution that is inside a foreach loop I have to store time span.
I am using following code
for (int i = 0; i < 100; i++)
{
DateTime start= DateTime.Now;
// Business logic
DateTime end= DateTime.Now;
TimeSpan time = start.Subtract(end);
// Save timespan in log file
}
Please correct me whether I am using right code, or do I need to modify for better performance and result.
You should use a Stopwatch. The Stopwatch is much more accurate for time measurement than the wall time clock.
var sw = Stopwatch.StartNew();
// business logic
sw.Stop();
TimeSpan time = sw.Elapsed;
The easiest way would be to:
TimeSpan time = DateTime.Now - start;
Alternatively, you could use a stopwatch which gives more accurate results. See http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx for how to work with a stopwatch.
It looks like you're using the timespan to measure performance. Your code is fine, however you should be aware that DateTimes are only so precise (about 10-15ms on most machines -- see the "Useless Timer Mechanism" section here for an explanation).
DateTimes are also not contiguous; what if the first DateTime is retrieved just before daylight savings time kicks in, and the latter one just after? An operation that takes one second could show up as taking an hour, or even negative time. Even with all times in UTC, there's potential problems when the user changes the time manually, or jumps caused by the computer going to sleep and waking up, etc.
A better alternative would be to use the Stopwatch class, which is designed for this sort of thing and uses a high-precision timer internally (via the QueryPerformanceCounter() Win32 function).
To answer your follow up questions, (1) you are correct, you do not need to reinstantiate a StopWatch every iteration. You just need to use the restart method, like so:
Stopwatch sw = new Stopwatch();
sw.Start(); // To initialize
for (int i = 0; i < 100; i++)
{
sw.Restart();
// Business logic
TimeSpan time = sw.Elapsed;
// Save timespan in log file
}
(2) You would probably have to write a few lines of code to return the value in seconds if less than one minute, and minutes if greater than, but here would be an example of doing that (assume this is the line right after saving the timespan from the above example):
TimeSpan time = sw.Elapsed;
int iSecondsOrMinutes = time.TotalSeconds < 60 ? time.Seconds : (int)time.TotalMinutes;
This example uses a Ternary Operator to save the integer for the amount of minutes or seconds.
In C++ I am able to get the current time when my application starts I can use
time_t appStartTime = time(null);
then to find the difference in seconds from when it started I can just do the same thing, then find the difference. It looks like I should be using "System.DateTime" in C# net, but the MSDN is confusing in its explanation.
How can I use System.DateTime to find the difference in time (in seconds) between when my application starts, and the current time?
Use Now property
DateTime startTime = DateTime.Now;
//work
DateTime currentTime = DateTime.Now;
and then just simply calculate the difference.
currentTime - startTime;
If you would like to measure the performance consider using Stopwatch.
Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//work
stopWatch.Stop();
As everyone suggested... But they were a little wrong :-) Use DateTime.UtcNow, because
It's faster (DateTime.Now calls DateTime.UtcNow)
It works around change of DST on/off.
OR
As #Shekhar_Pro suggested (yes, he was right!), use the Stopwatch
var sw = Stopwatch.StartNew()
.... your code
sw.Stop();
var ms = sw.ElapsedMilliseconds;
or
var ticks = sw.ElapsedTicks;
Oh... and I was forgetting... What you are doing is probably worthless in certain situation... You know, 2011 processors are multicore (and even 2010 :-) )... If you app is vaguely multithread you are probably better measuring:
Process.GetCurrentProcess().TotalProcessorTime
This include the use of all the cores used by your app... So on a dual core, using both cores, it will "gain" 2 seconds for every "real time" second.
If you are using this for checking performance and time taken to Execute code then you Best bet is to use StopWatch.
otherwise System.DateTime has a Subtract function which can be used to get a TimeSpan object or even a simple - (subtract) operator will do it.
Then that TimeSpan object has a property of TotalSeconds which you can use.
Several ways to do this:
Use DateTime.Now. Subtracting produces a TimeSpan. Takes 8 bytes of storage, times up to 8000 years, resolution of 1 millisecond but accurate to 1/64 second on most machines.
Use Environment.TickCount. Similar to time_t but relative from machine boot time. Takes 4 bytes of storage, times up to 24 days (49 with a cast), resolution and accuracy same as DateTime.
Use Stopwatch. Stored on the heap, resolution is machine dependent but almost always well below a microsecond. Accuracy isn't usually good but repeats decently, assume +/- 5%. Best used to measure small intervals for comparison.
Use timeGetTime. This requires pinvoke to use this multimedia timer. Similar to Environment.TickCount, you can get 1 msec accuracy by using timeBeginPeriod. This is not cheap since it has system-wide effects. Best avoided.
Keep in mind that process execution is subject to the vagaries of overall operating system load, your program is sharing resources with the other 70-odd processes that are running. Either DateTime or TickCount has plenty of accuracy for that.
DateTime startTime = DateTime.Now;
//some code
TimeSpan difference = DateTime.Now - startTime;
int seconds = difference.TotalSeconds.Truncate();
I want to measure the performance of my code.. if I consider the time as a criterion
I have this code
DateTime oldDate = new DateTime(2002,7,15);
DateTime newDate = DateTime.Now;
// Difference in days, hours, and minutes.
TimeSpan ts = newDate - oldDate;
// Difference in days.
int differenceInDays = ts.Milliseconds ;
Question1: is this the only way that I can test the performance of my algorithm ?
Question2: what are other criterion that C# provide to test the performance?
Regards
Its always better to use System.Diagnostics.Stopwatch
Check this link for more details. Performance Tests: Precise Run Time Measurements with System.Diagnostics.Stopwatch
use Stopwatch class
//Start a stopwatch:
var watch = Stopwatch.StartNew();
//Execute the code
watch.Stop(); //This stops the watch
The elapsed time can be measured by using Elapsed, ElapsedMilliSeconds and ElapsedTicks properties.
Try using the StopWatch class. It has significantly higher resolution than the DateTime and TimeSpan classes.
Additionally, you can look at the Windows Performance Counters as a way of measuring performance while your application is running so that you can monitor the health of your application.
You can use a profiler (tool based, for example with SlimTune) or measure the time with System.Diagnostics.Stopwatch. It has better precision than the DateTime hack.
If you truly want to use DateTime (because it's easier to use), use UtcNow instead of Now. It's a little faster (because current date and time are stored in UTC format in Windows) and as an added bonus, you can test your program around the DST change time :-).
But yeah, use Stopwatch.
Stopwatch watch = Stopwatch.StartNew();
watch.Stop()
Ah... very important... your code is wrong
ts.TotalMilliseconds
I did the same error yesterday, but I was measuring times around the second, so it was more difficult to notice :-)
I am trying to check how much time does a function takes to execute in my code :
I did this :
void foo()
{
int time = System.DateTime.Now.Millisecond;
// code of my function. do this, that, etc.
Console.WriteLine((System.DateTime.Now.Millisecond-time).ToString());
}
What i get is this :
-247
I don't understand why minus ??
& please tell me ways to measure time taken by a function.
& If pro-filer is an option then please recommend me some simple option.
Note : Here I have shown a console app but in practice i need for a Web App in ASP.NET which may be n-tier architecture also.
Thanks
DateTime.Millisecond returns the millisecond part of the current date/time, not the milliseconds since some previous date/time.
Use a Stopwatch:
var stopwatch = Stopwatch.StartNew();
// ...
Console.WriteLine(stopwatch.ElapsedMilliseconds);
You appear to be using and subtracting the current millisecond
e.g.
2010-01-01 00:00:00:999 -> System.DateTime.Now.Millisecond is 999
2010-01-01 00:00:01:000 -> System.DateTime.Now.Millisecond is 000
000 - 999 = -999; not terribly useful!
Using DateTime.Now to profile isn't recommended anyway. If you're just trying to get an idea, you probably want to look at System.Diagnostics.Stopwatch:-
void Foo()
{
Stopwatch myStopWatch = StopWatch.StartNew()
// Your code goes here;
Console.WriteLine(myStopWatch.ElapsedMilliseconds);
}
For "real world" use, though, you're best using a profiler.
DateTime.Millisecond returns the millisecond component of the current time.
In other words, it returns the total number of milliseconds mod 1,000.
For example, if you happen to get the property at the exact end of a second, it will be 0.
Instead, you should use the Stopwatch class.
The Millisecond property returns the milliseconds component of the date, i.e. a number between 0 and 999.
As others have said, you can use the StopWatch class, or you can call the DateTime.Subtract() method to obtain a TimeSpan instance, then use the TotalMilliseconds property of that instance to get the total elapsed milliseconds between your two times:
public void Foo()
{
DateTime then = DateTime.Now;
// ...
Console.WriteLine(DateTime.Now.Subtract(then).TotalMilliseconds);
}
You may want to use Stopwatch.
I am using Visual Studio Express Edition and it don't have any profiler or code analyzer.
Code having two delegate performing same task, one by using anonymous method and one by Lambda expression. I want to compare which one is taking less time.
How can I do this in VS express? (not only for delegate for methods also)
If it is Duplicate, please link it.
Thanks
I tried Like This:
/** Start Date time**/
DateTime startTime = DateTime.Now;
/********do the square of a number by using LAMBDA EXPRESSIONS********/
returnSqr myDel = x => x * x;
Console.WriteLine("By Lambda Expression Square of {0} is: {1}", a,myDel(a));
/** Stop Date time**/
DateTime stopTime = DateTime.Now;
TimeSpan duration = stopTime - startTime;
Console.WriteLine("Execution time 1:" + duration.Milliseconds);
/** Start Date time**/
DateTime startTime2 = DateTime.Now;
/*****do the square of a number by using ANONYMOUS EXPRESSIONS********/
returnSqr myDel1 = delegate(int x) { return x * x;};
Console.WriteLine("By Anonymous Method Square of {0} is: {1}", a, myDel1(a));
/** Stop Date time**/
DateTime stopTime2 = DateTime.Now;
TimeSpan duration2 = stopTime2 - startTime2;
Console.WriteLine("Execution Time 2:" + duration.Milliseconds);
Output gives:
Execution time 1 : 0
Execution time 2 : 0
Why like this?
You can use the stopwatch class.
Stopwatch sw = Stopwatch.StartNew();
// rest of the code
sw.Stop();
Console.WriteLine("Total time (ms): {0}", (long) sw.ElapsedMilliseconds);
use StopWatch class to start a timer before the code is run and stop it after the code has ended. Do this for both code snippets and find out which takes mroe time.
This is not a perfect solution but it helps
You might consider using the Scenario class which supports simple begin/end usage, with optional logging via ETW.
From their Wiki:
You can use the Scenario class to add performance instrumentation to an application (either .NET or native C++). The shortest description of a Scenario is "a named stopwatch that can log when you start and stop it".
Just using the stopwatch class should do the trick.
Most likely, your code is executing more quickly than the maximum resolution of your timing device. That's why it's reporting "0" milliseconds as the execution time for both pieces of code: the amount of time that has passed is undetectable. For some people, that might be enough to conclude it probably doesn't matter which way you do it.
However, if it's important to get an accurate comparison of each method's speed, you could try running the code in a tight loop. Essentially, do whatever it is you are doing about 100 or 1,000 or even a million times in a row, however many it takes to pass a sufficient amount of time that will register on your time-keeping device. Obviously, it won't take anywhere near that long to run the routine once or even several times in your final code, but at least it will give you an idea as to the relative speed of each option.