I want to meassure an average time of executing a task on 5 threads doing 100 tasks.
For time meassuring purposes I use nanoTime()
The task is calling one specific method, let's call it foo();
I don't create any additional classes.
In my code I create a task:
Runnable thExecute = new Runnable(){
@Override
public void run(){
foo();
}
};
And then I create a thread:
Thread th = new Thread(thExecute);
long start = System.nanoTime();
th.run();
long stop = System.nanoTime();
This would be great if I had the same number of tasks as threads. I tried to create arrays of threads and tasks:
Runnable[] thExecutes = new Runnable[100];
Thread[] ths = new Thread[5];
But now I don't know what to do next. I know they should be queued somehow and probably I should use Executor
class. I use Java 6.
Edit: At first I didn't mean what I wrote. Now I know I want average time + highest time.
First thing to note: you should not expect precise results, if you measure performance by yourself. There are tools that do it for you, providing much more reliable results.
If you want to do it by yourself, use ExecutorService:
ExecutorService service = Executors.newFixedThreadPool(5);
long startTs = System.nanoTime();
List<Future> futures = new ArrayList<>();
for (Runnable r : runnables) {
futures.add(service.submit(r));
}
for (Future f : futures) {
f.get();
}
long durationNs = System.nanoTime() - startTs;
And again: since you are measuring nanoseconds, I strongly encourage you to avoid manual measurements, because there are many factors that will spoil the results: no warmup, setup expenses, etc.
Update: to measure execution time of every task, you can submit Callable<Long>
instead of Runnable
public long call() {
long startTs = System.nanoTime();
// do the task
return System.nanoTime() - startTs;
}
Now Future will return the execution time, you can print it or gather in a list:
for (Future<Long> f : futures) {
long spentTime = f.get();
}
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