I am starting multiple threads(around 1000) from my code. They are Runnable threads called from a while loop. How do I calculate the total time taken for all threads to finish executing?
Also I am opening a DB Connection and have a set of queries for which I am starting these threads(1 thread for 1 query). When do I close the connection?
In general you cannot measure time execution exactly because context switching. If you have 1000 threads it is produce significant impact to all time measuring. Nevertheless if you may omit high exactness of time measuring you may use CountDownLautching primitive to synchronizing thread starting and thread finishing: Show activity on this post.
Record the total number of tasks. Let the total number of tasks be represented by "n". Add the task times recorded to obtain the total time (in minutes) taken to complete all the tasks. Calculate the arithmetic mean or the average time to complete one task by dividing the total time to complete all tasks by the number of tasks completed (n).
Decorator will take thread as an input function and in wrapper func we will calculate the execution time using python time module . We will then use this time decorator in our program to wrap worker method to measure its execution time and at the end we will take a look at the results.
Similar Tasks or Times. Calculate the arithmetic mean or the average time to complete one task by dividing the total time to complete all tasks by the number of tasks completed (n). For example, if three consecutive tasks took five minutes, six minutes, and nine minutes to complete, then the average time for one task would be 6.7 minutes,...
I would use an ExecutorService
long start = System.nanoTime();
ExecutorService service = Executors.newWhatEverPool();
for(loop)
service.submit(new MyRunnable());
service.shutdown();
service.awaitTermination(1, TimeUnit.HOUR); // or longer.
long time = System.nanoTime() - start;
System.out.printf("Tasks took %.3f ms to run%n", time/1e6);
Close the connection when you have finished with it. It is a common pattern for the creator of a resource to also close it. e.g. If the main thread creates the connection, it could close after all the threads have finished.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With