2

How do I do a thousandths of a second readout, as a timer, without allocating any garbage?

I understand that it's possible to build an array of strings, from 000 to 999 for the 0.999, and get the appropriate string of these for each/any thousandths of a second scenario, from the thousandthsArray[nnn]

However, how do I divide it out from each time report, each frame, without creating garbage in the process of dividing out the seconds.

eg. the current time is 14.397

I need to get at and separate out that 397 from the 14 seconds without creating any garbage.

But the maths functions seem to create a little garbage, each and every frame. And nothing I can think of is particularly optimal. Or even working.

Confused
  • 6,048
  • 6
  • 34
  • 75

2 Answers2

3

I don't think this is possible without creating any garbage. You should go for as little as possible.

You could use Mathf.Floor which rounds it down to the last int making it "forget" any decimals and then subtract it from the original value like

float time = 14.6978f;

float fullSeconds = Mathf.Floor(time);
// = 14 (rounded down)

int thousandthOfSeconds = Mathf.RoundToInt((time - fullSeconds) * 1000); 
// = 698 (rounded up)

that's at least way cheaper than dealing with any strings there.

derHugo
  • 83,094
  • 9
  • 75
  • 115
  • Excellent point about the number almost always being much more information than just thousandths of a second. I had totally forgotten about that. – Confused May 24 '19 at 08:15
  • Just looked more closely at Mathf, they have two things the same: Ceil and CeilToInt. No wonder there's garbage being made. – Confused May 24 '19 at 09:17
  • what do you mean? `Ceil` is kind of the opposide of `Floor` and `CailToInt` the opposide of `FloorToInt` (for always rounding up). It isn't exactly the same thing: `Floor` and `Ceil` still return `float` while `FloorToInt` and `RoundToInt` also includes a typecast to `int`. If you are okey with a float as return ofcourse you can use `Mathf,Round` as well – derHugo May 24 '19 at 09:21
  • Wait... I'm much more confused, now. – Confused May 24 '19 at 13:48
0

There are different ways to cleanup unmanaged resources:

Implement IDisposable interface and Dispose method 'using' block is also used to clean unmanaged resources There are couple of ways to implement Dispose method:

Implement Dispose using 'SafeHandle' Class (It is inbuilt abstract class which has 'CriticalFinalizerObject' and 'IDisposable' interface has been implemented) Object.Finalize method to be override (This method is clean unmanaged resources used by particular object before it is destroyed) Let's see below code to Dispose unmanaged resources:

Implement Dispose using 'SafeHandle' Class:

Shivam Dhagat
  • 121
  • 1
  • 1
  • 6