Linux 测量 C++ 代码的运行时间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11062804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Measuring the runtime of a C++ code?
提问by peaceman
I want to measure the runtime of my C++ code. Executing my code takes about 12 hours and I want to write this time at the end of execution of my code. How can I do it in my code?
我想测量我的 C++ 代码的运行时间。执行我的代码大约需要 12 个小时,我想在我的代码执行结束时编写这段时间。我怎样才能在我的代码中做到这一点?
Operating system: Linux
操作系统:Linux
回答by Kjir
I used something like this in one of my projects:
我在我的一个项目中使用了这样的东西:
#include <sys/time.h>
struct timeval start, end;
gettimeofday(&start, NULL);
//Compute
gettimeofday(&end, NULL);
double elapsed = ((end.tv_sec - start.tv_sec) * 1000)
+ (end.tv_usec / 1000 - start.tv_usec / 1000);
This is for milliseconds and it works both for C and C++.
这是毫秒,它适用于 C 和 C++。
回答by betabandido
If you are using C++11 you can use system_clock::now()
:
如果您使用的是 C++11,您可以使用system_clock::now()
:
auto start = std::chrono::system_clock::now();
/* do some work */
auto end = std::chrono::system_clock::now();
auto elapsed = end - start;
std::cout << elapsed.count() << '\n';
You can also specify the granularity to use for representing a duration:
您还可以指定用于表示持续时间的粒度:
// this constructs a duration object using milliseconds
auto elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
// this constructs a duration object using seconds
auto elapsed =
std::chrono::duration_cast<std::chrono::seconds>(end - start);
If you cannot use C++11, then have a look at chronofrom Boost.
如果您不能使用C ++ 11,然后看看时辰从升压。
The best thing about using such a standard libraries is that their portability is really high (e.g., they both work in Linux and Windows). So you do not need to worry too much if you decide to port your application afterwards.
使用这样一个标准库的最大好处是它们的可移植性非常高(例如,它们都可以在 Linux 和 Windows 下运行)。因此,如果您之后决定移植您的应用程序,则不必太担心。
These libraries follow a modern C++ design too, as opposed to C-like approaches.
这些库也遵循现代 C++ 设计,而不是类似 C 的方法。
EDIT:The example above can be used to measure wall-clock time. That is not, however, the only way to measure the execution time of a program. First, we can distinct between user and system time:
编辑:上面的例子可用于测量挂钟时间。然而,这并不是衡量程序执行时间的唯一方法。首先,我们可以区分用户时间和系统时间:
- User time:The time spent by the program running in user space.
- System time:The time spent by the program running in system (or kernel) space. A program enters kernel space for instance when executing a system call.
Depending on the objectives it may be necessary or not to consider system time as part of the execution time of a program. For instance, if the aim is to just measure a compiler optimization on the user code then it is probably better to leave out system time. On the other hand, if the user wants to determine whether system calls are a significant overhead, then it is necessary to measure system time as well.
根据目标,可能需要或不考虑将系统时间作为程序执行时间的一部分。例如,如果目标只是测量用户代码上的编译器优化,那么最好忽略系统时间。另一方面,如果用户想确定系统调用是否是一个重要的开销,那么也有必要测量系统时间。
Moreover, since most modern systems are time-shared, different programs may compete for several computing resources (e.g., CPU). In such a case, another distinction can be made:
此外,由于大多数现代系统是分时的,不同的程序可能会争夺多个计算资源(例如 CPU)。在这种情况下,可以进行另一种区分:
- Wall-clock time:By using wall-clock time the execution of the program is measured in the same way as if we were using an external (wall) clock. This approach does not consider the interaction between programs.
- CPU time:In this case we only count the time that a program is actually running on the CPU. If a program (P1) is co-scheduled with another one (P2), and we want to get the CPU time for P1, this approach does not include the time while P2 is running and P1 is waiting for the CPU (as opposed to the wall-clock time approach).
- 挂钟时间:通过使用挂钟时间,程序执行的测量方式与我们使用外部(挂钟)时钟相同。这种方法没有考虑程序之间的交互。
- CPU 时间:在这种情况下,我们只计算程序实际在 CPU 上运行的时间。如果一个程序 (P1) 与另一个程序 (P2) 被共同调度,并且我们想要获得 P1 的 CPU 时间,则这种方法不包括 P2 正在运行和 P1 等待 CPU 的时间(与挂钟时间方法)。
For measuring CPU time, Boost includes a set of extra clocks:
为了测量 CPU 时间,Boost包含一组额外的时钟:
process_real_cpu_clock
, captures wall clock CPU time spent by the current process.process_user_cpu_clock
, captures user-CPU time spent by the current process.process_system_cpu_clock
, captures system-CPU time spent by the current process. A tuple-like classprocess_cpu_clock
, that captures real, user-CPU, and system-CPU process times together.- A
thread_clock
thread steady clock giving the time spent by the current thread (when supported by a platform).
process_real_cpu_clock
, 捕获当前进程花费的挂钟 CPU 时间。process_user_cpu_clock
, 捕获当前进程花费的用户 CPU 时间。process_system_cpu_clock
, 捕获当前进程花费的系统 CPU 时间。一个类似于元组的类process_cpu_clock
,它同时捕获真实的、用户-CPU 和系统-CPU 处理时间。- 一个
thread_clock
线程稳定时钟,给出当前线程所花费的时间(当受平台支持时)。
Unfortunately, C++11 does not have such clocks. But Boost is a wide-used library and, probably, these extra clocks will be incorporated into C++1x at some point. So, if you use Boost you will be ready when the new C++ standard adds them.
不幸的是,C++11 没有这样的时钟。但是 Boost 是一个广泛使用的库,而且这些额外的时钟可能会在某个时候被合并到 C++1x 中。因此,如果您使用 Boost,那么当新的 C++ 标准添加它们时,您就准备好了。
Finally, if you want to measure the time a program takes to execute from the command line (as opposed to adding some code into your program), you may have a look at the timecommand, just as @B?ови? suggests. This approach, however, would not let you measure individual parts of your program (e.g., the time it takes to execute a function).
最后,如果您想测量从命令行执行程序所需的时间(而不是在程序中添加一些代码),您可以查看time命令,就像@B?ови? 建议。但是,这种方法不会让您测量程序的各个部分(例如,执行函数所需的时间)。
回答by B?ови?
You can use timeto start your program. When it ends, it print nice time statistics about program run. It is easy to configure what to print. By default, it print user and CPU times it took to execute the program.
您可以利用时间来启动您的程序。当它结束时,它会打印有关程序运行的良好时间统计信息。很容易配置要打印的内容。默认情况下,它会打印执行程序所需的用户和 CPU 时间。
EDIT : Take a note that every measure from the code is not correct, because your application will get blocked by other programs, hence giving you wrong values*.
编辑:请注意,代码中的每个度量都不正确,因为您的应用程序将被其他程序阻止,从而为您提供错误的值*。
*By wrong values, I meant it is easy to get the time it took to execute the program, but that time varies depending on the CPUs load during the program execution. To get relatively stable time measurement, that doesn't depend on the CPU load, one can execute the application using timeand use the CPU as the measurement result.
*通过错误的值,我的意思是很容易获得执行程序所需的时间,但该时间因程序执行期间 CPU 的负载而异。为了获得相对稳定的时间测量,不依赖于 CPU 负载,可以使用时间执行应用程序,并使用 CPU 作为测量结果。
回答by vitaut
Use std::chrono::steady_clock
and not std::chrono::system_clock
for measuring run time in C++11. The reason is (quoting system_clock
's documentation):
在 C++11 中使用std::chrono::steady_clock
and 不std::chrono::system_clock
测量运行时间。原因是(引用system_clock
的文档):
on most systems, the system time can be adjusted at any moment
在大多数系统上,系统时间可以随时调整
while steady_clock is monotonic and is better suited for measuring intervals:
而 stable_clock 是单调的,更适合测量间隔:
Class std::chrono::steady_clock represents a monotonic clock. The time points of this clock cannot decrease as physical time moves forward. This clock is not related to wall clock time, and is best suitable for measuring intervals.
类 std::chrono::steady_clock 表示单调时钟。这个时钟的时间点不会随着物理时间的前进而减少。此时钟与挂钟时间无关,最适合测量间隔。
Here's an example:
下面是一个例子:
auto start = std::chrono::steady_clock::now();
// do something
auto finish = std::chrono::steady_clock::now();
double elapsed_seconds = std::chrono::duration_cast<
std::chrono::duration<double> >(finish - start).count();
A small practical tip: if you are measuring run time and want to report seconds std::chrono::duration_cast<std::chrono::seconds>
is rarely what you need because it gives you wholenumber of seconds. To get the time in seconds as a double
use the example above.
一个实用的小技巧:如果您正在测量运行时间并想要报告秒数,std::chrono::duration_cast<std::chrono::seconds>
则很少需要,因为它为您提供了整数秒数。要以秒为单位获取时间,请double
使用上面的示例。
回答by rwp
You could also try some timer classes that start and stop automatically, and gather statistics on the average, maximum and minimum time spent in any block of code, as well as the number of calls. These cxx-rtimer classes are available on GitHub, and offer support for using std::chrono, clock_gettime(), or boost::posix_time as a back-end clock source.
您还可以尝试一些自动启动和停止的计时器类,并收集有关在任何代码块中花费的平均、最大和最小时间以及调用次数的统计信息。这些 cxx-rtimer 类在GitHub上可用,并支持使用 std::chrono、clock_gettime() 或 boost::posix_time 作为后端时钟源。
With these timers, you can do something like:
使用这些计时器,您可以执行以下操作:
void timeCriticalFunction() {
static rtimers::cxx11::DefaultTimer timer("expensive");
auto scopedStartStop = timer.scopedStart();
// Do something costly...
}
with timing stats written to std::cerr on program completion.
在程序完成时将计时统计信息写入 std::cerr。
回答by Timmmm
This is the code I use:
这是我使用的代码:
const auto start = std::chrono::steady_clock::now();
// Your code here.
const auto end = std::chrono::steady_clock::now();
std::chrono::duration<double> elapsed = end - start;
std::cout << "Time in seconds: " << elapsed.count() << '\n';
You don't want to use std::chrono::system_clock
because it is not monotonic! If the user changes the time in the middle of your code your result will be wrong - it might even be negative. std::chrono::high_resolution_clock
might be implemented using std::chrono::system_clock
so I wouldn't recommend that either.
您不想使用,std::chrono::system_clock
因为它不是单调的!如果用户在您的代码中间更改时间,您的结果将是错误的 - 它甚至可能是负数。std::chrono::high_resolution_clock
可能会使用实现,std::chrono::system_clock
所以我也不建议这样做。
This code also avoids ugly casts.
此代码还避免了丑陋的强制转换。
回答by Natan Ayalon
If you wish to print the measured time with printf(), you can use this:
如果你想用 printf() 打印测量的时间,你可以使用这个:
auto start = std::chrono::system_clock::now();
/* measured work */
auto end = std::chrono::system_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
printf("Time = %lld ms\n", static_cast<long long int>(elapsed.count()));