How do I measure execution time for each row in C# - c#

I have the following Selenium test:
[TestMethod]
public void Edit()
{
Driver.GoToAdministrera();
Driver.ClickLink(strings.ActorSettings);
Driver.SendKeysToId(text, "Attributes");
Driver.Navigate().Refresh();
Driver.AssertTextInId(string.Empty, "Attributes");
Driver.SendKeysToId(text, "Attributes");
Driver.ClickClass("submitbutton");
Thread.Sleep(3000);
Driver.Navigate().Refresh();
Driver.AssertTextInId(text, "Attributes");
}
It is slow and I want to analyze where the bottleneck is. I know I could profile the test, but that will give me some long stack-trace and hotspots. I just want to know how long the execution time is for each row.
I know I can use the StopWatch class. I can even do something like a help method for this:
protected static void Time(Action action)
{
var sw = new Stopwatch();
sw.Reset();
sw.Start();
action();
sw.Stop();
Console.WriteLine(sw.Elapsed + " " + action.Method.Name);
}
But this requires me to modify my test.
Does anyone know of a method to get the timings for each row in a piece of code executed?

If you use Visual Studio 2015 or later you can run the test under debugger and look for PerfTips values. Stepping from line to line you will get estimated value of elapsed time for each line of the test which is probably what you need.

DateTime start = DateTime.Now;
// Do Processing
Driver.GoToAdministrera();
DateTime end = DateTime.Now;
Console.WriteLine("Time taken : " + (end - start));

Related

Ways to approach a Stop watch test in the form of unit test

I'm very new to c# I've been tasked with creating a test that will tell me how long a search process takes. So I click a search button. Then I wait for the results to appear.
I'd like to try it in the form of a unit test with my triple A's The test ideally can take no longer than 3 seconds to complete it's search.
What would be the best way to approach this? and Would I need to do any setup before hand?
I just have the generic code so far.
[TestMethod]
public void LocationNameSearch()
{
//Arrange
//Act
//Assert
}}
UPDATE:
I'm having a go at trying to create a basic stop watch then I will build in the data i need from the dev code. Where am I going wrong with this assert?
[TestMethod]
public void LocationNameSearch()
{
// Create new stopwatch.
Stopwatch stopwatch = new Stopwatch();
// Begin timing.
stopwatch.Start();
// Do something.
for (int i = 0; i > 1000; i++)
{
}
// Stop timing.
stopwatch.Stop();
//Assert
Assert.AreEqual(stopwatch.Stop, 1);
}
This is not using the Stopwatch class but I prefer to use the [Timeout] attribute.
Usage:
[TestMethod]
[Timeout(3000)]
public void LocationNameSearch() { }
If the test takes longer than 3 seconds to complete, the test will fail.
The assert should check the Elapsed property of the stopwatch and compare it to the maximum time the process is allowed to take.

Is this the best way to get the time it takes to run an async task?

I want to find out how long it takes to execute my async tasks, so that I can improve on the execution time.
Please look at the test method and advise. Test background: I want to find out the user account manager from Active Directory given the sAMACcountName.
[TestMethod]
public async Task GetManagerAsync_TestMethod()
{
// connect to the Active Directory
var serviceUsers = new User(#"LDAP://XXXXXXXXX", #"USER", "PASSWORD");
// get the time before the start of operation
var sTime = DateTime.Now;
// perform the task
var task = await serviceUsers.GetManagerAsync(#"sAMAccountName");
// get the time after the operation
var eTime = DateTime.Now;
// get the time span between the start and end time
TimeSpan taskRunTime = eTime - sTime;
System.Diagnostics.Debug.WriteLine("Operation took {0} seconds", taskRunTime.TotalSeconds);
Assert.IsNotNull(task);
}
You should be using a Stopwatch instead.
var stopwatch = Stopwatch.StartNew();
var task = await serviceUsers.GetManagerAsync(#"sAMAccountName");
stopwatch.Stop();
var elapsed = stopwatch.Elapsed;
Not only is it more semantically correct, it's also way more accurate:
If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time.

How to check if specific time has passed

I am start my operation and one of the argument my command line application get is Number that represent how much time my operation need to run.
int duration = int.Parse(args[0]) // run my operation for this time in minutes
This is what i have try (not working):
...
DateTime start = DateTime.Now;
// check whether this time in minutes passed
if (start.Minute > duration )
break;
EDIT: use UtcNow
void DoWork(int durationInMinutes)
{
DateTime startTime = DateTime.UtcNow;
TimeSpan breakDuration = TimeSpan.FromMinutes(durationInMinutes);
// option 1
while (DateTime.UtcNow - startTime < breakDuration)
{
// do some work
}
// option 2
while (true)
{
// do some work
if (DateTime.UtcNow - startTime > breakDuration)
break;
}
}
For this you can use StopWatch by defining
StopWatch watch = new StopWatch();
watch.Start();
and where ever ur code finishes running write
watch.Stop();
By using stopwach you can see you are running time of your application in detail. Of course if I am correct to understand you.

Calculate code run time/speed

I am very curious about run time/speed about codes in ms visual studio.
As instance,
1. code:
byte[] buffer = new byte[4096];
var p = System.IO.Directory.GetFiles(directoryName);
2. code
var entry = new ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
If i run 1. code ı want to see "it's running time/speed 0.03 seconds"
If i run 2. code ı want to see "it's running time/speed 0.06 seconds"
Is there anything to calculate running time/speed of codes in c# without using timer ?
Any help will be appreciated.
Thanks.
The best thing to use for quickly profiling code is Stopwatch in System.Diagonstics
var sw = Stopwatch.StartNew();
///.... stuff
sw.Stop();
sw.ElapsedMilliseconds;
If this is something you may want to use in production, i'd recommend: http://miniprofiler.com/
You can use a Stopwatch for benchmarking code
var sw = Stopwatch.StartNew();
var entry = new ZipEntry(Path.GetFileName(file));
sw.Stop();
Console.WriteLine("Time to zip: {0}", sw.Elapsed);
You could create a helper method if you intend on doing using it a lot
public static TimeSpan Benchmark(Action action)
{
var sw = Stopwatch.StartNew();
action();
sw.Stop();
return sw.Elapsed;
}
...
var timeTaken = Benchmark(() => /* run some code */)
Typically one would use the stopwatch.startnew, stop, elapsedtime methods.
There are some profiling tools on the market, and microsoft also has its own built-in performance suite. The following link is a tutorial on how to set it up.
http://msdn.microsoft.com/en-us/library/ms182372.aspx

Measuring code execution time

I want to know how much time a procedure/function/order takes to finish, for testing purposes.
This is what I did but my method is wrong 'cause if the difference of seconds is 0 can't return the elapsed milliseconds:
Notice the sleep value is 500 ms so elapsed seconds is 0 then it can't return milliseconds.
Dim Execution_Start As System.DateTime = System.DateTime.Now
Threading.Thread.Sleep(500)
Dim Execution_End As System.DateTime = System.DateTime.Now
MsgBox(String.Format("H:{0} M:{1} S:{2} MS:{3}", _
DateDiff(DateInterval.Hour, Execution_Start, Execution_End), _
DateDiff(DateInterval.Minute, Execution_Start, Execution_End), _
DateDiff(DateInterval.Second, Execution_Start, Execution_End), _
DateDiff(DateInterval.Second, Execution_Start, Execution_End) * 60))
Can someone show me a better way to do this? Maybe with a TimeSpan?
The solution:
Dim Execution_Start As New Stopwatch
Execution_Start.Start()
Threading.Thread.Sleep(500)
MessageBox.Show("H:" & Execution_Start.Elapsed.Hours & vbNewLine & _
"M:" & Execution_Start.Elapsed.Minutes & vbNewLine & _
"S:" & Execution_Start.Elapsed.Seconds & vbNewLine & _
"MS:" & Execution_Start.Elapsed.Milliseconds & vbNewLine, _
"Code execution time", MessageBoxButtons.OK, MessageBoxIcon.Information)
A better way would be to use Stopwatch, instead of DateTime differences.
Stopwatch Class - Microsoft Docs
Provides a set of methods and properties that you can use to
accurately measure elapsed time.
// create and start a Stopwatch instance
Stopwatch stopwatch = Stopwatch.StartNew();
// replace with your sample code:
System.Threading.Thread.Sleep(500);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
Stopwatch measures time elapsed.
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();
// Begin timing
stopwatch.Start();
Threading.Thread.Sleep(500)
// Stop timing
stopwatch.Stop();
Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);
Here is a DEMO.
You can use this Stopwatch wrapper:
public class Benchmark : IDisposable
{
private readonly Stopwatch timer = new Stopwatch();
private readonly string benchmarkName;
public Benchmark(string benchmarkName)
{
this.benchmarkName = benchmarkName;
timer.Start();
}
public void Dispose()
{
timer.Stop();
Console.WriteLine($"{benchmarkName} {timer.Elapsed}");
}
}
Usage:
using (var bench = new Benchmark($"Insert {n} records:"))
{
... your code here
}
Output:
Insert 10 records: 00:00:00.0617594
For advanced scenarios, you can use BenchmarkDotNet or Benchmark.It or NBench
If you use the Stopwatch class, you can use the .StartNew() method to reset the watch to 0. So you don't have to call .Reset() followed by .Start(). Might come in handy.
If you are looking for the amount of time that the associated thread has spent running code inside the application.
You can use ProcessThread.UserProcessorTime Property which you can get under System.Diagnostics namespace.
TimeSpan startTime= Process.GetCurrentProcess().Threads[i].UserProcessorTime; // i being your thread number, make it 0 for main
//Write your function here
TimeSpan duration = Process.GetCurrentProcess().Threads[i].UserProcessorTime.Subtract(startTime);
Console.WriteLine($"Time caluclated by CurrentProcess method: {duration.TotalSeconds}"); // This syntax works only with C# 6.0 and above
Note: If you are using multi threads, you can calculate the time of each thread individually and sum it up for calculating the total duration.
Stopwatch is designed for this purpose and is one of the best way to measure execution time in .NET.
var watch = System.Diagnostics.Stopwatch.StartNew();
/* the code that you want to measure comes here */
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Do not use DateTimes to measure execution time in .NET.
Example for how one might use the Stopwatch class in VB.NET.
Dim Stopwatch As New Stopwatch
Stopwatch.Start()
''// Test Code
Stopwatch.Stop()
Console.WriteLine(Stopwatch.Elapsed.ToString)
Stopwatch.Restart()
''// Test Again
Stopwatch.Stop()
Console.WriteLine(Stopwatch.Elapsed.ToString)

Categories