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

Yil*_*riz 3 c c++

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

Sin*_*all 10

您可以使用clock()函数<time.h>
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;
Run Code Online (Sandbox Code Playgroud)

  • 这可能是系统相关的,但在Linux上,我发现clock()非常粗粒度(不准确),所以我避免使用它优先于其他系统函数,例如来自<sys/times.h的times() > (2认同)