- 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 elapsed time in nanoseconds with Java?
In general, the elapsed time is the time from the starting point to ending point of an event. Following are various ways to find elapsed time in Java −
The nanoTime() method returns the current time in nano seconds. To find the elapsed time for the execution of a method in nano seconds −
- Retrieve the current time using the nanoTime() method.
- Execute the desired method.
- Again, retrieve the current time using the nanoTime() method.
- Finally, Find the difference between the end value and the start value.
Example
public class Example { public void test(){ int num = 0; for(int i=0; i<=50; i++){ num =num+i; System.out.print(num+", "); } } public static void main(String args[]){ //Start time long begin = System.nanoTime(); //Starting the watch new Example().test(); //End time long end = System.nanoTime(); long time = end-begin; System.out.println(); System.out.println("Elapsed Time: "+time); } }
Output
0, 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136, 153, 171, 190, 210, 231, 253, 276, 300, 325, 351, 378, 406, 435, 465, 496, 528, 561, 595, 630, 666, 703, 741, 780, 820, 861, 903, 946, 990, 1035, 1081, 1128, 1176, 1225, 1275, Elapsed Time: 1530200
Advertisements