C语言 C程序的执行时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5248915/
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
Execution time of C program
提问by Roger
I have a C program that aims to be run in parallel on several processors. I need to be able to record the execution time (which could be anywhere from 1 second to several minutes). I have searched for answers, but they all seem to suggest using the clock()function, which then involves calculating the number of clocks the program took divided by the Clocks_per_secondvalue.
我有一个旨在在多个处理器上并行运行的 C 程序。我需要能够记录执行时间(可以是 1 秒到几分钟不等)。我已经搜索了答案,但他们似乎都建议使用该clock()函数,然后涉及计算程序占用的时钟数除以该Clocks_per_second值。
I'm not sure how the Clocks_per_secondvalue is calculated?
我不确定该Clocks_per_second值是如何计算的?
In Java, I just take the current time in milliseconds before and after execution.
在 Java 中,我只是在执行前后以毫秒为单位获取当前时间。
Is there a similar thing in C? I've had a look, but I can't seem to find a way of getting anything better than a second resolution.
C中有类似的东西吗?我已经看过了,但我似乎找不到比第二个分辨率更好的方法。
I'm also aware a profiler would be an option, but am looking to implement a timer myself.
我也知道分析器是一种选择,但我希望自己实现一个计时器。
Thanks
谢谢
回答by Thomas Pornin
CLOCKS_PER_SECis a constant which is declared in <time.h>. To get the CPU time used by a task within a C application, use:
CLOCKS_PER_SEC是在 中声明的常量<time.h>。要获取 C 应用程序中任务使用的 CPU 时间,请使用:
clock_t begin = clock();
/* here, do your time-consuming job */
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
Note that this returns the time as a floating point type. This can be more precise than a second (e.g. you measure 4.52 seconds). Precision depends on the architecture; on modern systems you easily get 10ms or lower, but on older Windows machines (from the Win98 era) it was closer to 60ms.
请注意,这将时间作为浮点类型返回。这可以比一秒更精确(例如,您测量 4.52 秒)。精度取决于架构;在现代系统上,您可以轻松获得 10 毫秒或更低,但在较旧的 Windows 机器上(从 Win98 时代开始),它更接近 60 毫秒。
clock()is standard C; it works "everywhere". There are system-specific functions, such as getrusage()on Unix-like systems.
clock()是标准C;它“无处不在”。有系统特定的功能,例如getrusage()在类 Unix 系统上。
Java's System.currentTimeMillis()does not measure the same thing. It is a "wall clock": it can help you measure how much time it took for the program to execute, but it does not tell you how much CPU time was used. On a multitasking systems (i.e. all of them), these can be widely different.
JavaSystem.currentTimeMillis()不测量相同的东西。它是一个“挂钟”:它可以帮助您测量程序执行所需的时间,但它不会告诉您使用了多少 CPU 时间。在多任务系统(即所有系统)上,这些可能有很大不同。
回答by S..K
If you are using the Unix shell for running, you can use the time command.
如果您使用 Unix shell 进行运行,则可以使用 time 命令。
doing
正在做
$ time ./a.out
assuming a.out as the executable will give u the time taken to run this
假设 a.out 作为可执行文件会给你时间来运行它
回答by Wes Hardaker
You functionally want this:
你在功能上想要这个:
#include <sys/time.h>
struct timeval tv1, tv2;
gettimeofday(&tv1, NULL);
/* stuff to do! */
gettimeofday(&tv2, NULL);
printf ("Total time = %f seconds\n",
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
Note that this measures in microseconds, not just seconds.
请注意,这以微秒为单位,而不仅仅是秒。
回答by Alexandre C.
In plain vanilla C:
在普通香草 C 中:
#include <time.h>
#include <stdio.h>
int main()
{
clock_t tic = clock();
my_expensive_function_which_can_spawn_threads();
clock_t toc = clock();
printf("Elapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC);
return 0;
}
回答by adimoh
Most of the simple programs have computation time in milli-seconds. So, i suppose, you will find this useful.
大多数简单程序的计算时间以毫秒为单位。所以,我想,你会发现这很有用。
#include <time.h>
#include <stdio.h>
int main(){
clock_t start = clock();
// Execuatable code
clock_t stop = clock();
double elapsed = (double)(stop - start) * 1000.0 / CLOCKS_PER_SEC;
printf("Time elapsed in ms: %f", elapsed);
}
If you want to compute the runtime of the entire program and you are on a Unix system, run your program using the timecommand like this time ./a.out
如果你想计算整个程序的运行时间并且你在 Unix 系统上,使用time命令运行你的程序,如下所示time ./a.out
回答by hklel
Thomas Pornin's answer as macros:
Thomas Pornin 作为宏的回答:
#define TICK(X) clock_t X = clock()
#define TOCK(X) printf("time %s: %g sec.\n", (#X), (double)(clock() - (X)) / CLOCKS_PER_SEC)
Use it like this:
像这样使用它:
TICK(TIME_A);
functionA();
TOCK(TIME_A);
TICK(TIME_B);
functionB();
TOCK(TIME_B);
Output:
输出:
time TIME_A: 0.001652 sec.
time TIME_B: 0.004028 sec.
回答by Stephen
A lot of answers have been suggesting clock()and then CLOCKS_PER_SECfrom time.h. This is probably a bad idea, because this is what my /bits/time.hfile says:
很多答案一直在建议clock(),然后CLOCKS_PER_SEC从time.h. 这可能是一个坏主意,因为这是我的/bits/time.h文件所说的:
/* ISO/IEC 9899:1990 7.12.1: <time.h>
The macro `CLOCKS_PER_SEC' is the number per second of the value
returned by the `clock' function. */
/* CAE XSH, Issue 4, Version 2: <time.h>
The value of CLOCKS_PER_SEC is required to be 1 million on all
XSI-conformant systems. */
# define CLOCKS_PER_SEC 1000000l
# if !defined __STRICT_ANSI__ && !defined __USE_XOPEN2K
/* Even though CLOCKS_PER_SEC has such a strange value CLK_TCK
presents the real value for clock ticks per second for the system. */
# include <bits/types.h>
extern long int __sysconf (int);
# define CLK_TCK ((__clock_t) __sysconf (2)) /* 2 is _SC_CLK_TCK */
# endif
So CLOCKS_PER_SECmight be defined as 1000000, depending on what options you use to compile, and thus it does not seem like a good solution.
所以CLOCKS_PER_SEC可能被定义为 1000000,这取决于你使用什么选项来编译,因此它似乎不是一个好的解决方案。
回答by JohnSll
(All answers here are lacking, if your sysadmin changes the systemtime, or your timezone has differing winter- and sommer-times. Therefore...)
(这里没有所有答案,如果您的系统管理员更改了系统时间,或者您的时区有不同的冬季和夏季时间。因此...)
On linux use: clock_gettime(CLOCK_MONOTONIC_RAW, &time_variable);It's not affected if the system-admin changes the time, or you live in a country with winter-time different from summer-time, etc.
linux使用:clock_gettime(CLOCK_MONOTONIC_RAW, &time_variable);系统管理员更改时间不受影响,或您居住在冬季与夏季不同的国家等。
#include <stdio.h>
#include <time.h>
#include <unistd.h> /* for sleep() */
int main() {
struct timespec begin, end;
clock_gettime(CLOCK_MONOTONIC_RAW, &begin);
sleep(1); // waste some time
clock_gettime(CLOCK_MONOTONIC_RAW, &end);
printf ("Total time = %f seconds\n",
(end.tv_nsec - begin.tv_nsec) / 1000000000.0 +
(end.tv_sec - begin.tv_sec));
}
man clock_gettimestates:
man clock_gettime状态:
CLOCK_MONOTONIC
Clock that cannot be set and represents monotonic time since some unspecified starting point. This clock is not affected by discontinuous jumps in the system time
(e.g., if the system administrator manually changes the clock), but is affected by the incremental adjustments performed by adjtime(3) and NTP.
回答by redent84
You have to take into account that measuring the timethat took a program to execute depends a lot on the load that the machine has in that specific moment.
您必须考虑到,测量程序执行所需的时间在很大程度上取决于机器在特定时刻的负载。
Knowing that, the way of obtain the current time in C can be achieved in different ways, an easier one is:
知道了,C中获取当前时间的方式可以有多种实现方式,比较简单的一种是:
#include <time.h>
#define CPU_TIME (getrusage(RUSAGE_SELF,&ruse), ruse.ru_utime.tv_sec + \
ruse.ru_stime.tv_sec + 1e-6 * \
(ruse.ru_utime.tv_usec + ruse.ru_stime.tv_usec))
int main(void) {
time_t start, end;
double first, second;
// Save user and CPU start time
time(&start);
first = CPU_TIME;
// Perform operations
...
// Save end time
time(&end);
second = CPU_TIME;
printf("cpu : %.2f secs\n", second - first);
printf("user : %d secs\n", (int)(end - start));
}
Hope it helps.
希望能帮助到你。
Regards!
问候!
回答by Shinnok
ANSI C only specifies second precision time functions. However, if you are running in a POSIX environment you can use the gettimeofday()function that provides microseconds resolution of time passed since the UNIX Epoch.
ANSI C 仅指定秒精度时间函数。但是,如果您在 POSIX 环境中运行,则可以使用gettimeofday()函数,该函数提供自 UNIX Epoch 以来经过的时间的微秒分辨率。
As a side note, I wouldn't recommend using clock() since it is badly implemented on many(if not all?) systems and not accurate, besides the fact that it only refers to how long your program has spent on the CPU and not the total lifetime of the program, which according to your question is what I assume you would like to measure.
作为旁注,我不建议使用 clock() 因为它在许多(如果不是全部?)系统上实现得很糟糕而且不准确,除了它仅指您的程序在 CPU 上花费的时间和不是程序的总生命周期,根据您的问题,这是我假设您想要衡量的。

