- 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
How to measure the time taken by a function in Java?
java.lang.System.currentTimeMillis() method can be used to compute the time taken by a function in java. Trick is simple. Get the before time and after time using currentTimeMillis() where before time is the time when method is invoked and after time is when method has executed. See the example below −
Example
public class Tester{ public static void main(String[] args) { long startTime = System.currentTimeMillis(); longRunningMethod(); long endTime = System.currentTimeMillis(); System.out.println("Time taken: " + (endTime -startTime) + " ms"); } private static void longRunningMethod() { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } }
Output
Time taken: 1000 ms
Advertisements