Question

Calculate Execution Time

Asked by: cstcfu

I would like to ask how to calculate the execution time of a fregment of the codes in UNIX environment using C language?

e.g. how to determine the execution time of the following codes? What functions should I insert in front and behind of the codes?

for(i=0; i<1000; i++)
   for(j=0; j<1000; j++)
      arr[j]*=arr[i];

<print out the time here!>


Thanks!

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2003-06-16 at 02:31:43ID20649268
Tags

execution

,

time

,

c

Topic

C Programming Language

Participating Experts
9
Points
50
Comments
16

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. C calculation
    F = 12,5 * 2 Exp ( x / 12 ) If I have x how do I calculate F if I only can use + * / - << >> in C ? I don't have access to the EXP function on my system. /FN
  2. Calculator
    Does anyone know of any calculator add-ins, formulas, scripts? I want a button or something in a form where the user could perform weight conversions. And if that's not possible what code would I use to bring up Window's Calculator? Thanks.
  3. "Timing" Calculation:
    Hi all, I need to perform some tasks to calculate the total time that needed to execute a specific method. But I am totaly no idea what kind of packages that I should use. I have tried to look into java..util.* and the Timer inside is to let me to schedule something and no...
  4. Time calculations
    Hi All, I'm pretty new to mysql (infact new to DB's in general). I'm trying to do a calculation. In a table I have to fields: StartTime and EndTime both fields are datetime formated fields. I'd like to work out the duration between the StartTime and EndTime so basically E...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: sangsvarPosted on 2003-06-16 at 02:42:08ID: 8730578

Performance is a class. It has 2 methods.

void Performance::start_measurement()
{
      start = clock();
}

double Performance::display_time_taken()
{
      double duration = 0;

      finish = clock();
   
   duration = (double)(finish - start) / CLOCKS_PER_SEC;

   return duration;
}

Performace pf;
pf.start_measurment();

for(i=0; i<1000; i++)
  for(j=0; j<1000; j++)
     arr[j]*=arr[i];

pf.display_time_taken();


 

by: akshayxxPosted on 2003-06-16 at 02:52:06ID: 8730636

a rough method wud be to .. print the times .. just before the loop and just after the loop ..
u can use time() function for this purpose .. if u want more accurate time . in microseconds .. then use gettimeofday()
look at the respective man pages

 

by: sunnycoderPosted on 2003-06-16 at 03:06:19ID: 8730713

If you wish to find time of execution of your program, use clock() function
1. It is provided in ANSI C standard and will be portable
2. It is built for exactly the purpose of finding execution time

printing current time just before of after code may not be good enough because your program may not be running all the time
other processes will get scheduled in between and all that will be counted as your execution time !!!

here is the help page for clock()

clock
clock_t clock (void)

HEADER      time.h

PURPOSE
To find out how long a program has been running.

RESULT
If successful, clock() returns the amount of time the program has been running, as an variable of type clock_t, otherwise it returns (clock_t)-1.

NOTES
To convert the value returned by clock() into seconds divide it by the macro CLOCKS_PER_SEC.

Function clock does not take any arguments and returns a value ot type clock_t, which is defined on /usr/include/sys/types.h and /usr/include/time.h as int. This function returns CPU time that elapsed since the execution of the program commenced. The returned time is not in seconds. It is in clock cycles. There is a constant CLOCKS_PER_SEC defined on /usr/include/time.h, which tells how many clock cycles there are per second. So, in order to find out how many CPU seconds you have used so far you have to divide the result obtained by calling clock by CLOCKS_PER_SEC.

to find time in milliseconds, just divide the result by (CLOCKS_PER_SEC/1000) instead of CLOCKS_PER_SEC .... viola !!


I have posted a detailed answer here ... have a look
http://www.experts-exchange.com/Programming/Q_20618373.html

 

by: SaltePosted on 2003-06-16 at 03:52:18ID: 8730895

Since this is a C forum and not C++ I wouldn't suggest a class.....

However, for your question there are two solutions.

gettimeofday() is available on some systems and get you a time measured in microseconds.

If you use intel pentium processor it has an instruction RDTSC that read a timer measured in 1/10th of a micro second. It is possible this instruction is privileged but it is also possible it isn't. If you can read it it gives you the best measurement by far since it has minimum overhead for the reading itself.

You can also consider using times() which can also be used for measuring time intervals.

Be aware that such a timing as you suggest to do is riddled with problems if you run on a regular OS such as windows and Unix (including Linux, Solaris, Aix, HPUX etc).

The problem is that you actually share the processor with other processes. It is possible that in the middle of the loop your process will be stopped and some other process take over. Suddenly you see a HUGE increase in the time.

If you want to average out such effects you should repeat the timing several times and compute the average rather than a single measurement.

Also, whatever method you use to measure the time make sure you also remove the time it takes to measure the time from your timing. In other words you first need to measure how long it takes to measure the time:

int i;
timer_type A = measure();
timer_type B = measure();
// B - A is the time it takes to call measure...

for (i = 0; i < N; ++i)
   do_job();

time_type C = measure();

// B - A is the time it takes to call measure().
// C - B is the time it takes to call measure + N * times of do_job.
// C - B - (B-A) == C - 2*B + A is the time to do the job N times.
double x = double(C + A - B - B)/N;

// x is the average time in units of timer_type for do_job. This also include time given to other processes
// on average, so don't be surprised if you extreme variation for small values of N. N must be fairly large
// before you get stable values. Also, because N must be large you should probably do the C + A - B - B arithmetic in 8 byte (64 bit) integers.

Hope this is of help.

Alf

 

by: sunnycoderPosted on 2003-06-16 at 04:27:06ID: 8731042

I still feel that a better way as compared to going through the statistical averaging is to use clock()
It will cut down your efforts, time required and will provide you exactly what you seek of it ... the execution time.

 

by: grg99Posted on 2003-06-16 at 05:02:09ID: 8731205

If that's all there is to the test program, you can use the shell command "time".
It would be best if you wrap the test code with a loop that goes around enough times to make the total run time several seconds.

One BIG gotcha:

THE CODE MUST DO SOMETHING USEFUL!

i.e.  if the code calculates some valyue, but doesnt do anything with the final result, a good optimizing compiler
may optimize out a lot of the code!
One way to guarantee that the code actually runs and a good way to check the accuracy of the compielr and optimizer),
is to add up the contents of the resulting array and printf() the result out.

 

by: AjarPosted on 2003-06-16 at 05:06:42ID: 8731226

For time with  precision in seconds

#include <sys/timeb.h>

int ftime(struct timeb *tp);

struct timeb time_before,timeafter;
long total_time_taken;

ftime(&time_before);

for(i=0; i<1000; i++)
  for(j=0; j<1000; j++)
     arr[j]*=arr[i];

ftime(&time_after);
/*Calculate the time difference in milliseconds */
total_time_taken = (time_after.time  - time_before.time) * 1000 +(time_after.millitm- time_before.millitm);






 

by: SaltePosted on 2003-06-16 at 05:10:54ID: 8731251

>> I still feel that a better way as compared to going through the statistical averaging is to use clock()
>> It will cut down your efforts, time required and will provide you exactly what you seek of it ... the execution time.

The averaging is not because of the exact function to measure the time (clock(), times(), RDTSC or whatever) but because the time it takes to do a specific job will vary a lot from time to time and the smaller the job is, the more it will vary relative to the length of the time it takes.

So even if you use clock() you still have to average out.

The only time you can avoid that is if you run in a controlled environment where you know you won't get suspended while another process takes over or if you can somehow count only the time that you run and ignore the time used by other processes. This is the big benifit of times() since one of the fields there measure the time used by your process.

Another way is to use MS-DOS or Windows 3.1 or some other non-multi-tasking OS where you have complete control.

Another way is to use an OS that support a begin_atomic_section() and end_atomic_section() where process scheduling is suspended between those two calls. I don't know of any OS that support such functions though and I am not sure I would want one that did.

Hope this explains.

Alf

 

by: cstcfuPosted on 2003-06-16 at 09:18:54ID: 8733021

I am using Sun Salaris Ultra5. As discussed, I would like to capture the actual processing time (not the duration of that code segment)

for a whole program, we can use: "timex prog" to capture the actual process time of the user program (where prog is the program name).

So, can we do the same thing for a code segment?

Thanks!

(PS: I must use C to do so, not C++)

 

by: SaltePosted on 2003-06-16 at 10:20:52ID: 8733405

yes, you can do the same for code segments.

I outlined in my previous posting how you could do it. The time command uses the times() function to compute the time and you can do the same.

However, I feel your statements are somewhat ambiguous:

>> I would like to ask how to calculate the execution time of a fregment of the codes in UNIX environment using C language?

This calls for calculating time DIFFERENCE. You compute the time before you start the fragment and the time after you're done and then calculate the difference between them. This means you want to calculate the duration of a code segment -  how long time does it take to execute this fragment of code.

>> I am using Sun Salaris Ultra5. As discussed, I would like to capture the actual processing time (not the duration of that code segment)

Here you state you do NOT want to compute the time difference. You want to capture "actual processing time". If "actual processing time" is not "duration of executing a given code segment" then what does it mean?

Also, you have to differentiate if you want to compute:

1. actual time it took to execute the fragment of code right now. If so you get a time that is only valid at this particular time. Next time you run it you may get a completely different time due to external circumstances.

2. Actual time it took, ignoring other processes execution time. I.e. you want to compute how much time it took while executing in your process. This time is more stable compared to 1 since it subtracts the time the CPU is busy executing other programs.

3. average time it takes to execute the code fragment. This value is also more stable than the 1st and it takes into account how much time the user must on average wait before the job is done. However, the time it took this exact time might vary from the computed average but over time and when you execute the job many times the average is a good estimate of how much time you will spend doing this task.

I would appreciate it if you could be more accurate when you describe what it is you want to measure.

From your reference to the time command and using times it suggest it is number 2 above you want to do. If so you can just call times() before and after and compute the time difference. You probably also want to remove the time it took to call times() if so I suggest you do it like I described above.

step 1. Call times() and store values in A.
step 2. Call times() again (no code between) and store values in B.
stpe 3. do the job.
step 4. Call times() and store values in C.
Time spend doing the job in step 3 is then (C - B) - (B - A) == C + A - B - B.

Hope this is of help.

Alf

 

by: sludinPosted on 2003-06-16 at 17:10:01ID: 8736298

In addition to all of that, and if all is lost, you can use a profiler to get the details.  For example:

> gcc -pg main.c
> ./a.out
> gprof gmon.out

It doesn't directly answer your question, but it may fit your need in certian cases.  Also, it is
easiest to use if you put the code in its own function which will skew the results a bit, but
then heisenberg rears his head all over the place.

-stephen

 

by: cstcfuPosted on 2003-06-17 at 00:29:03ID: 8738312

I am working with:
Actual time it took, ignoring other processes execution time. I.e. you want to compute how much time it took while executing in your process.

to using "measure" function and data type "timer_type"

with library should be included?

 

by: kingofcodePosted on 2003-07-10 at 15:18:24ID: 8897193

I think the question is how to obtain "cpu time" used and not "elapsed time" for the particular chunk of code.

 

by: SaltePosted on 2003-07-11 at 00:41:28ID: 8899814

If you want to find out how much time it took while executing your process you really should use the times() function which measures exactly that.

do times() before you do the job and times() after and subtract the two.

Preferably like this:


1. do times() when you start, I call this time A.
2. do times() again to find out how much time it takes to do times, call this time B.
3. loop N times (a thousand or million or so) and do the job over and over again.
4. do times() again, I call this time C.

B - A is the time it takes to do times.
C - B is the times it takes to do times + N * the time to do the job.
So C - B - (B - A) == A + C - 2*B == N * times to do the job.
so ((double)(A + C - 2 * B)) / N is the average time it takes to do the job.

Hope this is of help.

Alf

 

by: jmcgPosted on 2004-02-16 at 22:36:46ID: 10379551

Nothing has happened on this question in more than 7 months. It's time for cleanup!

My recommendation, which I will post in the Cleanup topic area, is to
split points between sunnycoder {http:#8730713} & Salte {http:#8730895} (acknowledging other good responses).

Please leave any comments here within the next four days.

PLEASE DO NOT ACCEPT THIS COMMENT AS AN ANSWER!

jmcg
EE Cleanup Volunteer

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...