حساب وقت التنفيذ في جافا: الطرائق والأمثلة على العالم الحقيقي
Table of Contents
إن قياس وقت تنفيذ المدونة أمر أساسي لتحقيق الأداء الأمثل في تطبيقات جافا، وهو يساعد المطورين على تحديد الاختناقات وتحسين الكفاءة، وتستكشف هذه المادة أساليب مشتركة لحساب وقت التنفيذ وتقدم أمثلة عملية.
استخدام النظام.
The System.nanoTime لوسائل ] method offers high-resolution time measurement, it returns the current value of the most precise available system timer, in nanoseconds. To measure execution time, record the start time before the code runs and the end time afterward. The difference indicates the elapsed time.
مثال:
Long startTime = System.nanoTime
/رمز لقياس ]
long endTime = System.nanoTime
طول المدة = نهاية - مرحلة بدء التشغيل؛]
استخدام النظام الحالي
The System.currentTimeMillis...] method provides the current time in milliseconds. It is less precise than but suitable for measuring longer durations. Similar to the previous method, record the start and end times around the code block.
مثال:
long startTime = System.currentTimeMilliss...]
/رمز لقياس ]
long endTime = System.currentTimeMillis مركّز؛]
طول المدة = نهاية - مرحلة بدء التشغيل؛]
(بإستعمال صف (جافا
وتقدم مجموعة Instant ] من java.time]] نهجاً عصرياً لقياس الوقت، وهي توفر الدقة في الثانية النانوية وتناسب قياس المدة.
مثال:
Instant start = Instant.now
/رمز لقياس ]
Instant end = Instant.now
مدة الوجبات = مدة الطول.between (start, end);]
معرض العالم الحقيقي
إفترضي أنكِ تريدين قياس المدة التي يستغرقها الأمر لفرز صفيفة كبيرة، باستخدام [(FLT:0)] System.nanoTime
int[] صفيفة = حرف جديد [1 000 000]؛ ]
// صفائف جمهور ]
Long startTime = System.nanoTime
Arrays.sort(array);]
long endTime = System.nanoTime
System.out.println ("Sorting took " + (endTime - startTime) + "Nnoseconds."]