Ravi Shakya
Ravi Shakya

Reputation: 53

How to get total time taken by single thread?

I have 100 files. Some files size are 1mb and some files size are 100mb. I want to read all files utilizing multi-threading and I want to know how much time a particular thread has taken to read a single file. Lastly, I want to print the time of that thread out.

Note : I don't want average of single file.

Upvotes: 2

Views: 910

Answers (1)

Impurity
Impurity

Reputation: 1122

Overview

So there are a few ways you could achieve this that depend on the level of accuracy you would need. Lets investigate below.

currentTimeMillis()

long start = System.currentTimeMillis();
// Your File Operation Logic
long end = System.currentTimeMillis();
long timeElapsed = end - start;

This approach measures wall-clock time so this could yield some inaccuracies, but for testing purposes this would likely be adequate. In addition, this will return the timeElapsed in milliseconds.

nanoTime()

long start = System.nanoTime();
// Your File Operation Logic
long end = System.nanoTime();
long timeElapsed = end - start;

This method differs from currentTimeMillis() because it measures in nanoseconds. In addition, the javadocs state:

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time

Instant & Duration

Instant start = Instant.now();
// Your File Operation Logic
Instant end = Instant.now();
long timeElapsed = Duration.between(start, end).toMillis();

These class' are immutable, thread-safe, and utilize their own time-scale. However, you must be on Java 8 or higher to utilize.

Implementation

  • For the thread operations, wrap the method that performs the file actions that you wish to measure with the above logic blocks.
  • I recommend creating a thread-safe collection (your implementation may vary) of time values that will be printed out at a later time. Utilizing print statements when measuring time/performance will yield very inaccurate results, and should be used after your calculations have occurred.

Upvotes: 2

Related Questions