0% found this document useful (0 votes)
40 views2 pages

Measuring Time

Uploaded by

bishshoy007
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views2 pages

Measuring Time

Uploaded by

bishshoy007
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Measuring Program Running Time in C/C++

As programmer, we usually want to measure the speed of our program in time (seconds).
C/C++ provides a useful function in timing. We can use the function

clock_t clock(void);

to get the CPU clock time. The idea is simple. Get the starting and the ending CPU clock
time then divide by constant CLOCKS_PER_SEC defined in the time.h header file.
Don’t forget to put #include <time.h>.

Source Code “time.cpp”


#include <iostream>
#include <time.h>

using namespace std;

int main()
{
clock_t start = clock();

// do something
//

clock_t ends = clock();


cout << "Running Time : "
<< (double) (ends - start) / CLOCKS_PER_SEC << endl;

return 0;
}

Creating a Simple Timer Program

We can modify the program above a little bit so that we can have a timer program that
measures the speed of the program. In order to create the timer, we should be able to call
other program inside our program. This can be done by this useful function

int system(const char *cmd)

which is declared in stdlib.h. Don’t forget to put #include <stdlib.h>.


Source Code “timer.cpp”

#include <iostream>
#include <time.h>
#include <stdlib.h>

using namespace std;

int main(int argc,char **argv)


{
if (argc != 2)
{
// incorrect command line-argument
cout << "Usage : timer <program_name>" << endl;
return 1;
}

// start the clock


cout << "Starting " << argv[1] << "..." << endl;
clock_t start = clock();

// start program
system(argv[1]);

// program ends and stop clock


clock_t ends = clock();
cout << "Running Time : "
<< (double) (ends - start) / CLOCKS_PER_SEC << endl;

return 0;
}

Done by Stephanus Indra.


© Copyright 2003 – SIWare, Inc.
All Rights Reserved.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy