Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to calculate the total time it takes for multiple threads to finish executing?

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?

like image 960
user1583803 Avatar asked Aug 08 '12 07:08

user1583803


People also ask

How to measure the time of execution of a thread?

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.

How do you calculate total time taken to complete a task?

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).

How to measure execution time of a method in Python?

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.

How do you calculate similar tasks or times?

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,...


1 Answers

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.

like image 102
Peter Lawrey Avatar answered Sep 21 '22 16:09

Peter Lawrey