C / C ++中的算法速度测试仪

我必须以毫秒为单位计算算法的速度。 在C ++ / C中,我该怎么做? 我需要在输入之前和输出之后写smth但是究竟是什么?

您可以使用 clock()函数
clock()显示自程序启动以来已经过了多少个刻度。 宏CLOCKS_PER_SEC包含每秒的滴答数,因此您实际上可以获得时间。

 //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; 

没有通用的方法来衡量确切的时间或滴答。 测量方法,操作系统和计算机上发生的其他事情(其他应用程序,图形输出,后台进程)将影响结果。 有很多方法可以做到“足够好”(在许多情况下)测量:

  • 库函数

    clock(…),clock_gettime(…)

来自标准的lib(在time.h )和

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

用于linux和其他unix系统(在sys/time.h )(根据Oleg的评论编辑

  • 硬件柜台:

     __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(); 

我更喜欢这种方法,因为它直接读取硬件计数器。

  • 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(); 

请记住,测量结果与时钟周期不一致。 即纳秒。 我总是将微秒(10e-6 s)计算为最小的合理时间单位。

请注意,您可以使用C ++ 11 chrono库中的日期和时间实用程序。 来自cppreference.com :

chrono库定义了三种主要类型(持续时间,时钟和时间点)以及实用程序函数和常见的typedef。

请参阅GCC 4.5.1中编译的文章中的示例

您可以使用此函数库:

 // clock.c #include  #include "clock.h" struct clock { clock_t c1, c2; }; void start(clock *this) { this->c1 = clock(); } void stop (clock *this) { this->c2 = clock(); } double print(clock *this) { return (double)(c1 - c2) / CLOCKS_PER_SEC; } // clock.h #ifndef CLOCK_H_INCLUDED # define CLOCK_H_INCLUDED typedef struct clock clock; extern void start(clock *); extern void stop (clock *); extern double print(clock *); #endif // CLOCK_H_INCLUDED 

但有时clock不是很适应:你可以使用你的系统function,这可以更准确。