Luke
Luke

Reputation: 2486

C# - Time calculation not working with TimeSpan.FromTicks DateTime

I am trying to calculate a video framerate in a program. To do this I take

DateTime.Now

at the beginning of a stream, and then again after every frame whilst also incrementing a framecounter.

Then I calculate the FPS like so:

int fps = (int)(frames / (TimeSpan.FromTicks(CurrentTime.Ticks).Seconds - TimeSpan.FromTicks(StartTime.Ticks).Seconds));

The problem is that I occassionally get a negative number out, meaning the start time must be later than the current time. How can this be the case? Does anyone know anough about these functions to explain?

Upvotes: 0

Views: 1337

Answers (3)

illegal-immigrant
illegal-immigrant

Reputation: 8234

You should consider using StopWatch for such needs, It has much better precision

Upvotes: 5

Francesco Baruchelli
Francesco Baruchelli

Reputation: 7468

Seconds gives you the seconds part of the TimeSpan, not the total duration of the TimeSpan converted in seconds. This means that Seconds will never be greater than 60.

Use TotalSeconds instead

Upvotes: 6

mtijn
mtijn

Reputation: 3678

The datetime functions are probably not precise enough for your needs, you may want to look into performance counters instead. I think the StopWatch class is what your looking for. System.Diagnostics.StopWatch. that is using the QueryPerformanceFrequency and QueryPerformanceCounter functions for the timing.

Upvotes: 3

Related Questions