hashgraph / hedera-services

Crypto, token, consensus, file, and smart contract services for the Hedera public ledger
Apache License 2.0
281 stars 125 forks source link

Convenience methods for metrics doing measurements #5313

Open swirlds-automation opened 1 year ago

swirlds-automation commented 1 year ago

A comment on a recent PR:

I wonder, if we want to move to the pattern that SignedStateMetrics has startXYZMeasurement(), stopXYZMeasurement() etc. and it does the calculation and conversion to ms instead of putting this between the program logic.

But this is more a general discussion point, nothing that needs to be addresses in this PR.

For metrics where we are attempting to measure the time required by an event, convenience functions would be helpful.

startMeasurement() and stopMeasurement() would be an improvement over our current code. But there are some limitations to this.

I suggest we have the startMeasurement() return an object, and then have a method on that object that we call when it is time to stop the measurement.

We could also make this object autocloseable, so you could do something like this:

public interface TimeMeasurement extends AutoCloseable {

   void close();
}
try (final TimeMeasurement timer = myMetric.startMeasurement()) {
   // do something we are attempting to measure
}

Another thing we could do, perhaps in addition to the strategy above, would be to add a helper method

public interface TimeMeasurement extends AutoCloseable {

    void close();

    default void measure(final Runnable runnable) {
        try {
            runnable.run();
        } finally {
            close();
        }
    }

      default <T> measure(final Supplier<T> method) {
          try {
              return method.get();
          } finally {
              close();
          }
     }
}

Then we could also use the pattern

myMetric.measure(() -> StateHasher.hash(state));
final Signature = myMetric.measure(() -> sigher.sign(state));
swirlds-automation commented 1 year ago

migrated from: url=https://github.com/swirlds/swirlds-platform/issues/6150 author:cody-littley, #:6150, createdAt:2022-10-12T14:34:16Z, updatedAt=2023-02-17T22:29:27Z labels=P2,New Feature,Migration:Base