Stopwatch not giving accurate times
hey everyone, im using stopwatch to measure total milliseconds, but the timing is way off. for example, when
increment
is 50k for this piece of code, i count 30 seconds irl but the console says 0.1105ms, which is not even close to correct
22 Replies
what is
Stopwatch
exactly?
the methods GetTimestamp
and GetElapsedTime
don't exist on System.Diagnostics.Stopwatch
yeah they do
im just using the Stopwatch from system.diagnostics
ah, they're static methods
yeah so when you do these 3 lines
then you literally measured the time from
long startTime = Stopwatch.GetTimestamp();
to TimeSpan elapsedTime = Stopwatch.GetElapsedTime(startTime);
which is basically non-existent
actually, nevermind, not thinking well today it seems
are you sure LinearSearch
takes that long?
and it's not something else?
what do you actually want to measure here?if
genItems
is what takes time, the start time should be defined before therea normal stopwatch instance would make this easier
stopwatches are also inaccurate in general and should not be used to benchmark code
im measuring linear search here, and even if i wasn't genItems doesn't take long (i know this from before manual timing)
i was using one lol but i had the same issue so I tried this and it didn't work either
what should I use instead because I need to measure the amount of time it takes for some data collection
can you show more context?
and doing it manually is not possible beacause with a small number of items (less than 1000 for example) its almost instant
we can't really tell you why
LinearSearch
is so fast if we don't know what it looks like
its just a simple for loop
to benchmark code, you want to use a dedicated library like benchmarkdotnet
$benchmark
Try BenchmarkDotNet if you want a sophisticated library for benchmarking https://github.com/dotnet/BenchmarkDotNet
okay ill take a look
thanks
i mean, is the item to find potentially very early in the array?
if it's found instantly, then of course it's gonna take no time at all
even with an array of 50k items, theres no way that method would take very long
(also that)
just_ero#0000
REPL Result: Success
Result: TimeSpan
Compile: 548.432ms | Execution: 49.352ms | React with ❌ to remove this embed.
that's 1.1ms
i tried it on 30k and counted the seconds, it was 3, and the code gave out 0.0278 ms
then it isn't
LinearSearch
that takes that longim gonna try moving the timestamp
turns out it was genItems lol, a small change I made made it take a lot longer
thanks for the help 👍