সাধারণত অ্যালাপসড টাইম বলতে একটি ইভেন্টের শুরু থেকে শেষ পর্যন্ত 걸린 সময় বোঝায়। জাভাতে এটি বের করার বিভিন্ন পদ্ধতি নিচে দেওয়া হলো:
currentTimeMillis() মেথড ব্যবহার
currentTimeMillis() মেথড বর্তমান সময় মিলিসেকেন্ডে রিটার্ন করে। মেথড এক্সিকিউশনের আগে ও পরে সময় নিয়ে পার্থক্য বের করুন।
উদাহরণ
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[]) {
long begin = System.currentTimeMillis();
new Example().test();
long end = System.currentTimeMillis();
long time = end - begin;
System.out.println();
System.out.println("অ্যালাপসড টাইম: " + time + " মিলি সেকেন্ড");
}
}
আউটপুট
অ্যালাপসড টাইম: 4 মিলি সেকেন্ড
nanoTime() মেথড ব্যবহার
nanoTime() মেথড বর্তমান সময় ন্যানোসেকেন্ডে রিটার্ন করে। একইভাবে পার্থক্য বের করুন।
উদাহরণ
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[]) {
long begin = System.nanoTime();
new Example().test();
long end = System.nanoTime();
long time = end - begin;
System.out.println();
System.out.println("অ্যালাপসড টাইম: " + time);
}
}
আউটপুট
অ্যালাপসড টাইম: 1530200
Instant ক্লাস ব্যবহার
Instant.now() বর্তমান সময় দেয়, Duration.between() দুটি সময়ের পার্থক্য বের করে।
উদাহরণ
import java.time.Duration;
import java.time.Instant;
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[]) {
Instant start = Instant.now();
new Example().test();
Instant end = Instant.now();
long time = Duration.between(start, end).toMillis();
System.out.println();
System.out.println(time + " মিলি সেকেন্ড");
}
}
আউটপুট
3 মিলি সেকেন্ড
StopWatch ক্লাস ব্যবহার (Apache Commons Lang)
Apache Commons লাইব্রেরিতে StopWatch ক্লাস থাকে যাতে start(), stop(), getTime() মেথড আছে।
Maven Dependency
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
উদাহরণ
import org.apache.commons.lang3.time.StopWatch;
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[]) {
StopWatch obj = new StopWatch();
obj.start();
new Example().test();
obj.stop();
System.out.println();
System.out.println("অ্যালাপসড টাইম: " + obj.getTime() + " মিলি সেকেন্ড");
}
}
আউটপুট
অ্যালাপসড টাইম: 1 মিলি সেকেন্ড