1

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.

  • 3
    You could have each thread log its start and end, assuming the logging framework you use supports multithreading. – Tim Biegeleisen Sep 12 '18 at 09:36
  • To add to @TimBiegeleisen 's comments you should reference https://stackoverflow.com/questions/565893/best-practices-for-java-logging-from-multiple-threads Also, consider setting logging for your imports. – Paul Bastide Sep 12 '18 at 09:40
  • Multithreading will only improve your performance between 2 to 4 threads depending on your drive type. Beyond that, more threads will yield poorer performance. There is a list of possible implementations in this answer https://stackoverflow.com/a/40597140/3867574 – Serg M Ten Sep 12 '18 at 09:46

1 Answers1

1

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.
Rakesh
  • 2,946
  • 2
  • 14
  • 28
Impurity
  • 815
  • 1
  • 9
  • 25