- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculate the execution time of a method in C#
Use Stopwatch class to measure time of execution of a method in .NET −
Stopwatch s = Stopwatch.StartNew();
Now set a function and use the ElapsedMilliseconds property to get the execution time in milliseconds −
s.ElapsedMilliseconds
Let us see the complete code −
Example
using System; using System.IO; using System.Diagnostics; public class Demo { public static void Main(string[] args) { Stopwatch s = Stopwatch.StartNew(); display(); for (int index = 0; index < 5; index++) { Console.WriteLine("Time taken: " + s.ElapsedMilliseconds + "ms"); } s.Stop(); } public static void display() { Console.WriteLine("Demo function!"); } }
Output
Demo function! Time taken: 15ms Time taken: 16ms Time taken: 16ms Time taken: 16ms Time taken: 16ms
Advertisements