谁能告诉我如果我在下面的几行中错过双倍会发生什么?
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
我试图计算我的排序问题的运行时间,却忘记了类型转换为加倍。代码运行了将近 90 分钟,但打印的输出时间为“270.000006”。谁能帮我弄清楚这 270 意味着什么?
它有时也会显示“-ve”值。这个问题的任何解决方案。
编辑 - 我正在对 10^9 和 10^10 数字进行排序,因此代码将运行数小时。
如果代码运行了将近 90 分钟,您将在 72 分钟内获得 32 位架构上的 clock_t 类型溢出。我相信这是你的情况。
Correct usage is:
clock_t begin, end;
double time_spent;
begin = clock();
/* actual task that needs to be monitored */
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC; // in seconds
You are measuring CPU time here, not the elapsed time which includes I/O time as well. CLOCKS_PER_SEC is a constant which is declared in . The computation needs to be done in floating point arithmetic. Another alternative to compute timing is to use the time command.