Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

algorithm speed tester in C/C++

Tags:

c++

c

I have to calculate speed of my algorithm in base of milliseconds. In C++/C , how can i do this? I need to write smth before input and after output but what exactly??

like image 922
Yilmaz Paçariz Avatar asked Jul 23 '12 08:07

Yilmaz Paçariz


3 Answers

You could use clock() function from <time.h>
clock() shows how many ticks have passed since your program started. The macro CLOCKS_PER_SEC contains the number of ticks per second, so you can actually get time.

//We start measuring here. Remember what was the amount of ticks in the 
//beginning of the part of code you want to test:
int start = clock();
//<...>
//Do your stuff here
//<...>
int end = clock();//Now check what amount of ticks we have now. 
//To get the time, just subtract start from end, and divide by CLOCKS_PER_SEC.
std::cout << "it took " << end - start << "ticks, or " << ((float)end - start)/CLOCKS_PER_SEC << "seconds." << std::endl;
like image 175
SingerOfTheFall Avatar answered Sep 21 '22 17:09

SingerOfTheFall


There is no general way to measure the exact time or ticks. The method of measurement, the operating system and the other things happening on your computer (other application, graphical output, background processes) will influence the result. There is different ways to do "good-enough" (in many cases) measurements:

  • library functions

    clock(...), clock_gettime(...)

from the standard lib (in time.h) and

gettimeofday(..) // for elapsed (wallclock) time
times(..) // process times

for linux and other unix systems (in sys/time.h) (edited according to Oleg's comment)

  • hardware counter:

    __inline__ uint64_t rdtsc(void) {
      uint32_t lo, hi;
      __asm__ __volatile__( // serialize
                    "xorl %%eax,%%eax \n        cpuid":::"%rax",
                    "%rbx", "%rcx", "%rdx");
      __asm__ __volatile__("rdtsc":"=a"(lo), "=d"(hi));
      return (uint64_t) hi << 32 | lo;
    }
    
    /*...*/
    uint64_t t0 = rdtsc();
    code_to_be_tested();
    uint64_t t1 = rdtsc();
    

I prefer this method as it reads directly the hardware counter.

  • for C++11: std:chrono::highresolution_clock

    typedef std::chrono::high_resolution_clock Clock;
      auto t0 = Clock::now();
      code_to_be_tested();
      auto t1 = Clock::now();
    

Keep in mind, that the measurements will not be exact to the clockcycle. i.e. nanosecond. I always calculate microseconds (10e-6 s) as the smallest reasonable time unit.

like image 42
steffen Avatar answered Sep 19 '22 17:09

steffen


Note that you can use date and time utilities from C++11 chrono library. From cppreference.com:

The chrono library defines three main types (durations, clocks, and time points) as well as utility functions and common typedefs.

See the sample from the article compiled in GCC 4.5.1 here

like image 44
SChepurin Avatar answered Sep 19 '22 17:09

SChepurin