我必须以毫秒为单位计算我的算法的速度。在 C++/C 中,我该怎么做?我需要在输入之前和输出之后写smth,但究竟是什么?
4 回答
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;
没有通用的方法来测量确切的时间或刻度。测量方法、操作系统和计算机上发生的其他事情(其他应用程序、图形输出、后台进程)都会影响结果。有多种方法可以进行“足够好”(在许多情况下)测量:
库函数
时钟(...),clock_gettime(...)
从标准库(在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();
我更喜欢这种方法,因为它直接读取硬件计数器。
对于 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 库定义了三种主要类型(持续时间、时钟和时间点)以及实用函数和常用类型定义。
请参阅此处以 GCC 4.5.1 编译的文章中的示例
您可以使用此函数库:
// clock.c
#include <time.h>
#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
不是很适应:您可以使用您的系统功能,这可以更准确。