An warware: auna lokacin kisa

Auna Lokacin Kisa a Java aiki ne na yau da kullun ga masu haษ“akawa da yawa. Wannan yana da mahimmanci don kimanta aikin lambar ku, gano ฦ™ulla-ฦ™ulla, da haษ“aka ingantaccen sa. Yana da mahimmanci musamman lokacin haษ“aka aikace-aikace masu saurin lokaci inda aiki zai iya yin tasiri kai tsaye akan ฦ™warewar mai amfani.

Yana da mahimmanci don fahimtar maษ“alli na ma'aunin lokaci a Java kuma a yi amfani da ษ—akunan karatu da ayyuka masu dacewa, saboda rashin amfani na iya haifar da sakamako mara kyau. Bari mu bincika yadda ake auna lokacin kisa daidai.

Fahimtar System.nanoTime da System.currentTimeMillis

ฦŠaya daga cikin mafi yawan hanyoyin da ake amfani da su don auna lokacin aiwatarwa a Java ita ce ta amfani da ayyukan ajin na yanzuTimeMillis() da nanoTime() na System.

The System.currentTimeMillis() Hanyar tana dawo da lokacin na yanzu a cikin milli seconds daga Epoch (Janairu 1, 1970, 00:00:00 GMT). Yana da sauฦ™i don amfani amma yana da ฦ™ananan daidaito.

long start = System.currentTimeMillis();

// your code here

long end = System.currentTimeMillis();
System.out.println("Execution time in milliseconds: " + (end - start));

A wannan bangaren, System.nanoTime() yana ba da daidaito mafi girma kuma yana auna lokacin a nanoseconds.

long start = System.nanoTime();

// your code here

long end = System.nanoTime();
System.out.println("Execution time in nanoseconds: " + (end - start));

Aiki tare da Java Time API

Wani zaษ“i don auna lokacin kisa a Java yana amfani da API Time Java, ษ“angaren Java 8 da sama. Wannan API yana da amfani lokacin da muke buฦ™atar ฦ™arin iko akan ฦ™ididdiga na kwanan wata da lokaci.

Ana iya amfani da ajin kai tsaye don ษ—aukar tambarin lokaci na yanzu da auna lokacin aiwatarwa.

Instant start = Instant.now();

// your code here

Instant end = Instant.now();
System.out.println("Execution time in milli seconds: " + Duration.between(start, end).toMillis());

Guava Stopwatch Utility

Laburaren Guava daga Google ya haษ—a da aji mai amfani mai amfani don ayyukan lokaci mai suna Stopwatch. Yana da sauฦ™i kuma mai sauฦ™i don amfani kuma yana ba da madaidaicin ฦ™idayar lokaci.

Stopwatch stopwatch = Stopwatch.createStarted();

// your code here

stopwatch.stop(); // optional
System.out.println("Execution time in nanoseconds: " + stopwatch.elapsed(TimeUnit.NANOSECONDS));

Ta hanyar fahimta da amfani da waษ—annan ayyuka da ษ—akunan karatu, mutum zai iya auna daidai lokacin aiwatarwa da yin gyare-gyare masu dacewa don inganta aikin lamba a Java. Yana da mahimmanci a tuna cewa waษ—annan hanyoyin suna ba da lokacin agogon bango ne kawai (ainihin lokacin da ya wuce), kuma ga mafi yawan madaidaicin sakamakon la'akari da abubuwa kamar lokacin CPU, sauya mahallin, tarin shara, da lokacin dumi na JVM.

Shafi posts:

Leave a Comment