【问题标题】:For simple C cmd programs: how to add "program executed in 12,345 seconds"?对于简单的 C cmd 程序:如何添加“程序在 12,345 秒内执行”?
【发布时间】:2010-04-17 19:23:29
【问题描述】:

我是 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 位兼容性。 提前致谢!

【问题讨论】:

  • 有人,添加标签'c'
  • 如果您打算切换到 GNU Linux,您将能够使用“时间”命令。

标签: c time benchmarking execution-time elapsedtime


【解决方案1】:

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();
}

【讨论】:

    【解决方案2】:

    它在某些 PC 上不起作用的原因是...... 在

    上查看我的答案

    How precise is the internal clock of a modern PC?

    【讨论】:

      【解决方案3】:
      #include <mmsystem.h>
      
      int
      main() {
          DWORD start = timeGetTime();
          //Do work
          DWORD end = timeGetTime(); 
          printf("execution time: %.3f s\n", float(end - start) / 1000.0f);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-12
        • 1970-01-01
        • 1970-01-01
        • 2013-09-04
        • 1970-01-01
        • 1970-01-01
        • 2012-01-30
        • 1970-01-01
        相关资源
        最近更新 更多