Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I count how many milliseconds it takes my program to run?

Tags:

c++

timer

This will show how many seconds:

#include <iostream>
#include <time.h>
using namespace std;
int main(void)
{
    int times,timed;

    times=time(NULL);
    //CODE HERE

    timed=time(NULL);
    times=timed-times;
    cout << "time from start to end" << times;
}

This will show how many ticks:

#include <iostream>
#include <time.h>
using namespace std;
int main(void)
{
    int times,timed;

    times=clock();
    //CODE HERE

    timed=clock();
    times=timed-times;
    cout << "ticks from start to end" << times;
}

How do I get milliseconds?

like image 799
SomeUser Avatar asked Oct 04 '09 15:10

SomeUser


People also ask

Can you count milliseconds?

Yes, many watches with stopwatch function can measure time in units upto milliseconds, and are routinely used in sports events, competitions, including international and olympic events.

How do you measure time in milliseconds?

How to Convert Hours to Milliseconds. To convert an hour measurement to a millisecond measurement, multiply the time by the conversion ratio. The time in milliseconds is equal to the hours multiplied by 3,600,000.

How do you calculate running time of an algorithm in C++?

measure execution time of a program. Using time() function in C & C++. time() : time() function returns the time since the Epoch(jan 1 1970) in seconds. Prototype / Syntax : time_t time(time_t *tloc);

How do I track my CPP time?

Using <time. The function clock() returns the number of clock ticks since the program started executing. If you divide it by the constant CLOCKS_PER_SEC you will get how long the program has been running, in seconds.


2 Answers

Refer to question "Convert Difference between 2 times into Milliseconds" on Stack Overflow.

Or use this:

static double diffclock(clock_t clock1,clock_t clock2)
{
    double diffticks=clock1-clock2;
    double diffms=(diffticks)/(CLOCKS_PER_SEC/1000);
    return diffms;
}
like image 144
Satbir Avatar answered Sep 22 '22 21:09

Satbir


If you use a Unix OS, like Linux or Mac OS X, you can go to the command line and use the line

time call-program

The time command times how long the execution of any command line takes, and reports that to you.

I don't know if there's something like that for Windows, nor how you can measure miliseconds inside a C/C++ program, though.

like image 43
jpmelos Avatar answered Sep 20 '22 21:09

jpmelos