473,703 Members | 2,863 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using clock() to measure run time

I'm using the function clock() to measure the run time of a program so that
I can compare among several different algorithms. My code looks like:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h>

int main() {
clock_t start, stop;
double t = 0.0;

/* Start timer */
assert((start = clock())!=-1);

/* Do lotsa fancy calculations */

/* Stop timer */
stop = clock();
t = (double) (stop-start)/CLOCKS_PER_SEC;

printf("Run time: %f\n", t);

return(0);
} /* main */

The question is, does this give me the "real life" time that passes while
the process is excuting, or just the processor time actully used by this
process. Put another way, if I run the exact same code when the machine is
"idle" and again when the processor is being shared by a bunch of other
processes, will the above give me *roughly* the same results or a
significantly longer time for the latter case?

Thanx all!

--

Charles M. Reinke
Georgia Institute of Technology
School of Electrical and Computer Engineering
(404) 385-2579

Nov 14 '05 #1
6 61822
Charles M. Reinke <cm******@ece.g atech.edu> wrote:
I'm using the function clock() to measure the run time of a program so that
I can compare among several different algorithms. My code looks like: #include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h> int main() {
clock_t start, stop;
double t = 0.0; /* Start timer */
assert((start = clock())!=-1); /* Do lotsa fancy calculations */ /* Stop timer */
stop = clock();
t = (double) (stop-start)/CLOCKS_PER_SEC; printf("Run time: %f\n", t); return(0);
} /* main */ The question is, does this give me the "real life" time that passes while
the process is excuting, or just the processor time actully used by this
process. Put another way, if I run the exact same code when the machine is
"idle" and again when the processor is being shared by a bunch of other
processes, will the above give me *roughly* the same results or a
significantly longer time for the latter case?


clock() is supposed the CPU time, not the wallclock time, so it should
not matter (too much) if the machine is under load or not. Here are the
relevant sentences from the C89 standard:

The clock function returns the implementation' s best approximation
to the processor time used by the program since the beginning of an
implementation-defined era related only to the program invocation. To
determine the time in seconds, the value returned by the clock
function should be divided by the value of the macro CLK_TCK. If the
processor time used is not available or its value cannot be
represented, the function returns the value (clock_t)-1.

Please note that here you're asked to divide by CLK_TCK, not
CLOCKS_PER_SEC. In the C99 standard it tells you instead to divide by
CLOCKS_PER_SEC and if it is defined I would prefer it over CLK_TCK,
it also being required by the (newer) POSIX standard.

Regards, Jens
--
\ Jens Thoms Toerring ___ Je***********@p hysik.fu-berlin.de
\______________ ____________ http://www.toerring.de
Nov 14 '05 #2
>I'm using the function clock() to measure the run time of a program so that
I can compare among several different algorithms. My code looks like:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <time.h>

int main() {
clock_t start, stop;
double t = 0.0;

/* Start timer */
assert((start = clock())!=-1);

/* Do lotsa fancy calculations */

/* Stop timer */
stop = clock();
t = (double) (stop-start)/CLOCKS_PER_SEC;

printf("Run time: %f\n", t);

return(0);
} /* main */

The question is, does this give me the "real life" time that passes while
the process is excuting, or just the processor time actully used by this
process.
clock() is supposed to give an approximation to processor time used.
On a uni-tasking machine (e.g. MS-DOS), it may give something more
like wall clock time. On a multi-processor machine it may run
faster than real time. In that sense, clock() is like an employee
time clock (or the game clock in basketball, football, or whatever):
it runs only some of the time, is likely to only run 8 hours on a
weekday, and if you've got multiple employees, they may rack up
more than 24 hours of work in 1 day.
Put another way, if I run the exact same code when the machine is
"idle" and again when the processor is being shared by a bunch of other
processes, will the above give me *roughly* the same results or a
significantl y longer time for the latter case?


Generally, I'd say yes, assuming the OS makes an attempt to measure
actual CPU time (UNIX does, and I think recent versions of Windows
do also, assuming the C implementation uses the features), you get
roughly the same results, subject to things like task switching
messing up the cache so a run with a lot of task switches has a lot
more cache misses. There is also the issue of what process the
task switch itself gets "charged" to.

Gordon L. Burditt
Nov 14 '05 #3
"Gordon Burditt" <go***********@ burditt.org> wrote in message
news:11******** ****@corp.super news.com...

clock() is supposed to give an approximation to processor time used.
On a uni-tasking machine (e.g. MS-DOS), it may give something more
like wall clock time. On a multi-processor machine it may run
faster than real time. In that sense, clock() is like an employee
time clock (or the game clock in basketball, football, or whatever):
it runs only some of the time, is likely to only run 8 hours on a
weekday, and if you've got multiple employees, they may rack up
more than 24 hours of work in 1 day.
Generally, I'd say yes, assuming the OS makes an attempt to measure
actual CPU time (UNIX does, and I think recent versions of Windows
do also, assuming the C implementation uses the features), you get
roughly the same results, subject to things like task switching
messing up the cache so a run with a lot of task switches has a lot
more cache misses. There is also the issue of what process the
task switch itself gets "charged" to.

Gordon L. Burditt


Your explanation was very helpful. I'm using Linux on a dual-processor
machine, so I think I should be OK.

-Charles
Nov 14 '05 #4
<Je***********@ physik.fu-berlin.de> wrote in message
news:3f******** ****@uni-berlin.de...
case?

clock() is supposed the CPU time, not the wallclock time, so it should
not matter (too much) if the machine is under load or not. Here are the
relevant sentences from the C89 standard:

The clock function returns the implementation' s best approximation
to the processor time used by the program since the beginning of an
implementation-defined era related only to the program invocation. To
determine the time in seconds, the value returned by the clock
function should be divided by the value of the macro CLK_TCK. If the
processor time used is not available or its value cannot be
represented, the function returns the value (clock_t)-1.

Please note that here you're asked to divide by CLK_TCK, not
CLOCKS_PER_SEC. In the C99 standard it tells you instead to divide by
CLOCKS_PER_SEC and if it is defined I would prefer it over CLK_TCK,
it also being required by the (newer) POSIX standard.

Regards, Jens


Thanx, this is exactly what I was looking for. BTW, I tried CLK_TCK in
place of CLOCKS_PER_SEC and got something that looked more like microseconds
rather than sec. I think I'll stick with CLOCKS_PER_SEC, since I don't
really need that much precision for processes that take 28+ min. (in
parallel over 4 processors) to run. :^)

-Charles
Nov 14 '05 #5
"Charles M. Reinke" <cm******@ece.g atech.edu> writes:
<Je***********@ physik.fu-berlin.de> wrote in message
news:3f******** ****@uni-berlin.de...
case?

clock() is supposed the CPU time, not the wallclock time, so it should
not matter (too much) if the machine is under load or not. Here are the
relevant sentences from the C89 standard:

The clock function returns the implementation' s best approximation
to the processor time used by the program since the beginning of an
implementation-defined era related only to the program invocation. To
determine the time in seconds, the value returned by the clock
function should be divided by the value of the macro CLK_TCK. If the
processor time used is not available or its value cannot be
represented, the function returns the value (clock_t)-1.

Please note that here you're asked to divide by CLK_TCK, not
CLOCKS_PER_SEC. In the C99 standard it tells you instead to divide by
CLOCKS_PER_SEC and if it is defined I would prefer it over CLK_TCK,
it also being required by the (newer) POSIX standard.

Regards, Jens


Thanx, this is exactly what I was looking for. BTW, I tried CLK_TCK in
place of CLOCKS_PER_SEC and got something that looked more like microseconds
rather than sec. I think I'll stick with CLOCKS_PER_SEC, since I don't
really need that much precision for processes that take 28+ min. (in
parallel over 4 processors) to run. :^)


Watch out for overflow. If clock_t is a 32-bit signed integer type
and CLOCKS_PER_SEC is 1000000 (1e6), then it will overflow in less
than 36 minutes; assuming signed integer overflow wraps around, you
can get repeated results in less than 72 minutes.

This program will show the characteristics of the clock_t type.

#include <time.h>
#include <stdio.h>
#include <limits.h>

int main(void)
{
int bits = sizeof(clock_t) * CHAR_BIT;
if ((clock_t)1 / 2 > 0) {
printf("clock_t is a %d-bit floating-point type\n", bits);
}
else {
printf("clock_t is a %d-bit %s integer type\n",
bits, (clock_t)-1 < 0 ? "signed" : "unsigned") ;
}
printf("CLOCKS_ PER_SEC = %ld\n", (long)CLOCKS_PE R_SEC);
return 0;
}

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Nov 14 '05 #6
"Keith Thompson" <ks***@mib.or g> wrote in message
news:ln******** ****@nuthaus.mi b.org...

Watch out for overflow. If clock_t is a 32-bit signed integer type
and CLOCKS_PER_SEC is 1000000 (1e6), then it will overflow in less
than 36 minutes; assuming signed integer overflow wraps around, you
can get repeated results in less than 72 minutes.

Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst> San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst> We must do something. This is something. Therefore, we must do this.


Thanx for the warning. I've already experienced overflow when running on
only 1 processor, but it gave a negative number so knew what was going on
immediately. I didn't know how many times it had wrapped around though (and
it wasn't worth the effort to code around the problem), so I just threw
those results out.

<OT>
BTW, I noticed you're at SDSC--I'll be at ORNL this summer to test the 3D
parallel version of our code on their machines (current version is 2D).
It'll be *fun* to get off the beowulf cluster and work with a "real"
supercomputer for a while.
</OT>

-Charles
Nov 14 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
3404
by: peterbe | last post by:
What's the difference between time.clock() and time.time() (and please don't say clock() is the CPU clock and time() is the actual time because that doesn't help me at all :) I'm trying to benchmark some function calls for Zope project and when I use t0=time.clock(); foo(); print time.clock()-t0 I get much smaller values than when I use time.clock() (most of them 0.0 but some 0.01) When I use time.time() I get values like...
2
1830
by: bluekite2000 | last post by:
I ran the following code for a square matrix whose size ranges from 1x1 to 1000x1000 start=clock(); //sequential access time measurement for (i=0;i<Msize;i++) for(j=0;j<Nsize;j++) { Matrixj]=1;
1
1617
by: Dave H | last post by:
I have a generic class similar to below that is responsible for returning classes as Interfaces, where IBook and ICard are known interfaces. public sealed class StoreManager { private StoreManager() { } public IBook GetBook() {
3
3862
by: Steve | last post by:
I used the QueryPerformanceCounter and QueryPerformanceFrequency methods in my VC++ 6.0 projects to measure correct time spans, for example for timeouts, how much time takes to execute certain method etc I wonder whether there is something similar in .NET to measure time spans? Meantime I still use these methods through DllImport private static extern bool QueryPerformanceFrequency(out long lpFrequency);
2
2071
by: AndersBj | last post by:
I have a web application (asp.net) that uses Forms authentication to authenticate users against an Active Directory. The problem I have is that most of the time this works great, but every once in a while users cannot log on, they receive a time out message instead. Sometimes restarting the IIS solves the problem; sometimes this doesn't help at all. I'm very confused as what is causing this behaviour, I suspect that it is not code related,...
8
46802
by: saurabh.ss | last post by:
Hi I want to measure the time required to execute a piece of code. For example, I want to know the time required to execute a given function. How do I do it within C++? I know I got to use a library called ctime. But I dont know what functions to use. Please tell me.
1
1920
by: tommyjoe | last post by:
I am stuck. I can't get the program to show the tenths of a second correct. Any help would be appreciated! Here is the code: Option Compare Database Option Explicit Private Sub Form_Timer() Dim curTime As Date Dim Valhours As Integer Dim valminutes As Integer
1
1549
by: anthonypolidori | last post by:
i need to measure time in c# please tell me how to do it how do i print statements i need to create fault s this is console writing
8
1796
reginaldmerritt
by: reginaldmerritt | last post by:
I'm in the process of planning out a database that can organise our staff bookings. Basically having the ability to link staff to certain clients at chosen periods of time. For example StaffMemberA may be booked to with ClientA on 01/01/09 from 08:00 to 20:00. This data could be held in the table tbBookings with Primary keys StaffMemberName and Date. What i want the program to do is to tell the user if StaffMemberA is already booked in the...
0
9234
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9089
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8941
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7832
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5910
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4668
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3107
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2406
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2037
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.