C程序的执行时间 [英] Execution time of C program
问题描述
我有一个C计划,旨在将并行在几个处理器上运行。我需要能够记录的执行时间(可以是至数分钟从1秒的任何地方)。我已经寻找答案,但他们似乎都使用时钟()函数,然后包括计算时钟程序拿了由Clocks_per_second值除以数量建议。
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_second value.
我不知道该Clocks_per_second价值是如何计算的?
I'm not sure how the Clocks_per_second value is calculated?
在Java中,我只拿以毫秒为单位的当前时间之前和执行之后。有没有在C类似的事情?我一看,但我似乎无法找到得到任何东西比第二分辨率更好的方式。
In Java, I just take the current time in milliseconds before and after execution. 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.
我也知道一个分析器将是一种选择,但我希望实现一个定时器我自己。
I'm also aware a profiler would be an option, but am looking to implement a timer myself.
感谢
推荐答案
CLOCKS_PER_SEC
是在宣告一个恒定< time.h中>
。为了得到一个C应用程序中使用由任务的CPU时间,使用方法:
CLOCKS_PER_SEC
is a constant which is declared in <time.h>
. To get the CPU time used by a task within a C application, use:
clock_t begin = clock();
/* here, do your time-consuming job */
clock_t end = clock();
double time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
请注意,这个返回时间作为浮点类型。这可以更precise大于第二(例如在测量4.52秒)。 precision取决于建筑风格;现代系统你轻松搞定为10ms或更低,但旧的Windows机器(从Win98中的时代)是接近60ms的。
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.
时钟()
是标准的C;它的工作原理无处不在。有一些特定的系统功能,例如的getrusage()
的类Unix系统的。
clock()
is standard C; it works "everywhere". There are system-specific functions, such as getrusage()
on Unix-like systems.
Java的 System.currentTimeMillis的()
不测量同样的事情。这是一个挂钟:它可以帮助你衡量多少时间把该程序来执行,但它不会告诉你多少CPU时间使用。在多任务系统(即所有的人),这些都可以广泛不同。
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.
这篇关于C程序的执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!