तरीकों के निष्पादन समय की गणना करने के लिए जावा प्रोग्राम

इस उदाहरण में, हम जावा में सामान्य तरीकों और पुनरावर्ती विधियों के निष्पादन समय की गणना करना सीखेंगे।

इस उदाहरण को समझने के लिए, आपको निम्नलिखित जावा प्रोग्रामिंग विषयों का ज्ञान होना चाहिए:

  • जावा के तरीके
  • जावा पुनर्मिलन

उदाहरण 1: जावा प्रोग्राम विधि निष्पादन समय की गणना करने के लिए

 class Main ( // create a method public void display() ( System.out.println("Calculating Method execution time:"); ) // main method public static void main(String() args) ( // create an object of the Main class Main obj = new Main(); // get the start time long start = System.nanoTime(); // call the method obj.display(); // get the end time long end = System.nanoTime(); // execution time long execution = end - start; System.out.println("Execution time: " + execution + " nanoseconds"); ) )

आउटपुट

 विधि निष्पादन समय की गणना: निष्पादन समय: 656100 नैनोसेकंड

उपरोक्त उदाहरण में, हमने एक विधि बनाई है जिसका नाम है display()। विधि कंसोल के लिए एक कथन प्रिंट करता है। कार्यक्रम विधि के निष्पादन समय की गणना करता है display()

यहां, हमने कक्षा की पद्धति nanoTime()का उपयोग किया है SystemnanoTime()विधि नैनोसेकंड में चल JVM की वर्तमान मान देता है।

उदाहरण 2: पुनरावर्ती विधि के निष्पादन समय की गणना करें

 class Main ( // create a recursive method public int factorial( int n ) ( if (n != 0) // termination condition return n * factorial(n-1); // recursive call else return 1; ) // main method public static void main(String() args) ( // create object of Main class Main obj = new Main(); // get the start time long start = System.nanoTime(); // call the method obj.factorial(128); // get the end time long end = System.nanoTime(); // execution time in seconds long execution = (end - start); System.out.println("Execution time of Recursive Method is"); System.out.println(execution + " nanoseconds"); ) )

आउटपुट

 पुनरावर्ती विधि का निष्पादन समय 18600 नैनोसेकंड है

उपरोक्त उदाहरण में, हम नाम के पुनरावर्ती विधि के निष्पादन समय की गणना कर रहे हैं factorial()

दिलचस्प लेख...