Expiring Today—Celebrate National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

# Measure time (ms) to complete task

Posted on 2003-12-12
Medium Priority
900 Views
Hi, I have console program that I'll try to optimizie for speed. I need a way to measure how long it takes to complete certain tasks. I'd like to be able to say something like this anywhere in the code:

// Start counting from here

// Do something...

// Report time in milliseconds here

Ideas? I've been looking at the Timer class, but since these are just temporary checks, I'd rather not put everything in a while block. I hope there's a way to just get the time at two points and subtract the first from the second.
0
Question by:liljegren
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

Expert Comment

ID: 9927620
long begtime=System.DateTime.Now.Ticks;

// do something

long endtime=System.DateTime.Now.Ticks;

long ergtime=endtime-begtime;
double ergsec=Math.Round((double)ergtime/10000000D,2);

gives you the time in seconds with 2 commas
0

LVL 20

Accepted Solution

TheAvenger earned 500 total points
ID: 9927819
DateTime start = DateTime.Now;

// do something

TimeSpan timeElapsed = DateTime.Now - start;

timeElapsed.ToString() -> gives you the time in the format [-][d.]hh:mm:ss[.ff]
timeElapsed.Seconds, Milliseconds, Minutes, Days, Hours, Ticks, etc. can give you all the info you may need.

0

LVL 18

Expert Comment

ID: 9927980
You'd better use Hi Performance Timer since the Datetime object can measure up to 10ms accuracy.
http://www.codeproject.com/csharp/highperformancetimercshar.asp
0

LVL 20

Expert Comment

ID: 9928039
testn, there is always something to learn from you! 10x although your answer was not accepted!
0

Author Comment

ID: 9928062
Yes, thanks for the link testn. For now, the answer from TheAvenger is good enough for me, but I'll check it later.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developer portfolios can be a bit of an enigma—how do you present yourself to employers without burying them in lines of code?  A modern portfolio is more than just work samples, it’s also a statement of how you work.
Curious about the latest ransomware attack? Check out our timeline of events surrounding the spread of this new virus along with tips on how to mitigate the damage.