我是 Windows 用户,正在学习 C。我在家使用 Codeblocks 和 visual c++ 2008 express 编写简单的 C 命令行程序(我是初学者),我发现当 codeblocks 添加一个最后几行显示了它所花费的时间(例如:“进程返回 0 (0x0) 执行时间:6.848 秒”)。
我想将此功能添加到 .exe,以便我可以在几台计算机上“基准测试”或“测试”该程序。 我尝试使用 time(NULL),但它只能以 1 秒的精度工作。
我在这里也找到了非常有趣的答案(实际上我也在寻找同样的东西):Calculating time by the C++ code
Mark Wilkins 提出的解决方案在我的 windows 64 位 PC 上的 visual c++ 2008 express 上运行良好,但 .exe 在其他任何地方都无法运行。我做错了什么吗?
我想要一种方法来计算我的程序经过的墙时间,它必须具有 32 位兼容性。 提前致谢!
最佳答案
time.h 头文件中有一个函数 clock_t 时钟();
它返回自程序启动以来过期的一些硬件定时器时钟 要获得实时,您可以将该数字除以常数 CLOCKS_PER_SEC,该常数也在 time.h 中定义
完整的方法是:
void print_time_since_launch() {
printf ("Execution time %f", clock() / CLOCKS_PER_SEC);
}
你可以像这样在你的程序中使用它:
static clock_t s_start_time;
void start_clock() { s_start_time = clock(); }
void display_execution_time() {
clock_t now = clock();
double secs = (now - s_start_time) / (double)CLOCKS_PER_SEC;
printf("Execution time: %g secs\n", secs);
}
int main() {
start_clock();
/* do your thing */
display_execution_time();
}
关于c - 对于简单的 C cmd 程序 : how to add "program executed in 12,345 seconds"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2659683/