calculate method execution time in Visual Studio Express (No profiler available)? - c#

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.

Related

What is Best way to calculate time span

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.

Using c# System.DateTime like c++ time_t

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();

algorithm performance c#

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 :-)

Measure Time Taken By A Function And Don'T Understand Why Time Difference is Negative

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.

How frequent is DateTime.Now updated ? or is there a more precise API to get the current time?

I have code running in a loop and it's saving state based on the current time. Sometimes this can be just milliseconds apart, but for some reason it seems that DateTime.Now will always return values of at least 10 ms apart even if it's only 2 or 3 ms later. This presents a major problem since the state i'm saving depends on the time it was saved (e.g. recording something)
My test code that returns each value 10 ms apart:
public static void Main()
{
var dt1 = DateTime.Now;
System.Threading.Thread.Sleep(2);
var dt2 = DateTime.Now;
// On my machine the values will be at least 10 ms apart
Console.WriteLine("First: {0}, Second: {1}", dt1.Millisecond, dt2.Millisecond);
}
Is there another solution on how to get the accurate current time up to the millisecond ?
Someone suggested to look at the Stopwatch class. Although the Stopwatch class is very accurate it does not tell me the current time, something i need in order to save the state of my program.
Curiously, your code works perfectly fine on my quad core under Win7, generating values exactly 2 ms apart almost every time.
So I've done a more thorough test. Here's my example output for Thread.Sleep(1). The code prints the number of ms between consecutive calls to DateTime.UtcNow in a loop:
Each row contains 100 characters, and thus represents 100ms of time on a "clean run". So this screen covers roughly 2 seconds. The longest preemption was 4ms; moreover, there was a period lasting around 1 second when every iteration took exactly 1 ms. That's almost real-time OS quality!1 :)
So I tried again, with Thread.Sleep(2) this time:
Again, almost perfect results. This time each row is 200ms long, and there's a run almost 3 seconds long where the gap was never anything other than exactly 2ms.
Naturally, the next thing to see is the actual resolution of DateTime.UtcNow on my machine. Here's a run with no sleeping at all; a . is printed if UtcNow didn't change at all:
Finally, while investigating a strange case of timestamps being 15ms apart on the same machine that produced the above results, I've run into the following curious occurrences:
There is a function in the Windows API called timeBeginPeriod, which applications can use to temporarily increase the timer frequency, so this is presumably what happened here. Detailed documentation of the timer resolution is available via the Hardware Dev Center Archive, specifically Timer-Resolution.docx (a Word file).
Conclusions:
DateTime.UtcNow can have a much higher resolution than 15ms
Thread.Sleep(1) can sleep for exactly 1ms
On my machine, UtcNow grows grow by exactly 1ms at a time (give or take a rounding error - Reflector shows that there's a division in UtcNow).
It is possible for the process to switch into a low-res mode, when everything is 15.6ms-based, and a high-res mode, with 1ms slices, on the fly.
Here's the code:
static void Main(string[] args)
{
Console.BufferWidth = Console.WindowWidth = 100;
Console.WindowHeight = 20;
long lastticks = 0;
while (true)
{
long diff = DateTime.UtcNow.Ticks - lastticks;
if (diff == 0)
Console.Write(".");
else
switch (diff)
{
case 10000: case 10001: case 10002: Console.ForegroundColor=ConsoleColor.Red; Console.Write("1"); break;
case 20000: case 20001: case 20002: Console.ForegroundColor=ConsoleColor.Green; Console.Write("2"); break;
case 30000: case 30001: case 30002: Console.ForegroundColor=ConsoleColor.Yellow; Console.Write("3"); break;
default: Console.Write("[{0:0.###}]", diff / 10000.0); break;
}
Console.ForegroundColor = ConsoleColor.Gray;
lastticks += diff;
}
}
It turns out there exists an undocumented function which can alter the timer resolution. I haven't investigated the details, but I thought I'd post a link here: NtSetTimerResolution.
1Of course I made extra certain that the OS was as idle as possible, and there are four fairly powerful CPU cores at its disposal. If I load all four cores to 100% the picture changes completely, with long preemptions everywhere.
The problem with DateTime when dealing with milliseconds isn't due to the DateTime class at all, but rather, has to do with CPU ticks and thread slices. Essentially, when an operation is paused by the scheduler to allow other threads to execute, it must wait at a minimum of 1 time slice before resuming which is around 15ms on modern Windows OSes. Therefore, any attempt to pause for less than this 15ms precision will lead to unexpected results.
IF you take a snap shot of the current time before you do anything, you can just add the stopwatch to the time you stored, no?
You should ask yourself if you really need accurate time, or just close enough time plus an increasing integer.
You can do good things by getting now() just after a wait event such as a mutex, select, poll, WaitFor*, etc, and then adding a serial number to that, perhaps in the nanosecond range or wherever there is room.
You can also use the rdtsc machine instruction (some libraries provide an API wrapper for this, not sure about doing this in C# or Java) to get cheap time from the CPU and combine that with time from now(). The problem with rdtsc is that on systems with speed scaling you can never be quite sure what its going to do. It also wraps around fairly quickly.
All that I used to accomplish this task 100% accurately is a timer control, and a label.
The code does not require much explanation, fairly simple.
Global Variables:
int timer = 0;
This is the tick event:
private void timeOfDay_Tick(object sender, EventArgs e)
{
timeOfDay.Enabled = false;
timer++;
if (timer <= 1)
{
timeOfDay.Interval = 1000;
timeOfDay.Enabled = true;
lblTime.Text = "Time: " + DateTime.Now.ToString("h:mm:ss tt");
timer = 0;
}
}
Here is the form load:
private void DriverAssignment_Load(object sender, EventArgs e)
{
timeOfDay.Interval= 1;
timeOfDay.Enabled = true;
}
Answering the second part of your question regarding a more precise API, the comment from AnotherUser lead me to this solution that in my scenario overcomes the DateTime.Now precision issue:
static FileTime time;
public static DateTime Now()
{
GetSystemTimePreciseAsFileTime(out time);
var newTime = (ulong)time.dwHighDateTime << (8 * 4) | time.dwLowDateTime;
var newTimeSigned = Convert.ToInt64(newTime);
return new DateTime(newTimeSigned).AddYears(1600).ToLocalTime();
}
public struct FileTime
{
public uint dwLowDateTime;
public uint dwHighDateTime;
}
[DllImport("Kernel32.dll")]
public static extern void GetSystemTimePreciseAsFileTime(out FileTime lpSystemTimeAsFileTime);
In my own benchmarks, iterating 1M, it returns on an average 3 ticks vs DateTime.Now 2 ticks.
Why 1600 is out of my jurisdiction, but I use it to get the correct year.
EDIT: This is still an issue on win10. Anybody interested can run this peace of evidence:
void Main()
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(Now().ToString("yyyy-MM-dd HH:mm:ss.fffffff"));
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fffffff"));
Console.WriteLine();
}
}
// include the code above
You could use DateTime.Now.Ticks, read the artical on MSDN
"A single tick represents one hundred nanoseconds or one ten-millionth of a second."

Categories