windows 运行 C 程序的时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2591373/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 14:14:18  来源:igfitidea点击:

Elapsed time of running a C program

cwindowstimeelapsed

提问by yCalleecharan

I would like to know what lines of C code to add to a program so that it tells me the total time that the program takes to run. I guess there should be counter initialization near the beginning of main and one after the main function ends. Is the right header clock.h?

我想知道将哪些 C 代码行添加到程序中,以便它告诉我程序运行所需的总时间。我想应该在 main 开始附近和 main 函数结束后进行计数器初始化。是正确的标题clock.h吗?

Thanks a lot...

非常感谢...

UpdateI have a Win Xp machine. Is it just adding clock()at the beginning and another clock()at the end of the program? Then I can estimate the time difference. Yes, you're right it's time.h.

更新我有一台 Win Xp 机器。它只是clock()在程序的开头添加和另一个clock()在程序末尾添加吗?然后我可以估计时差。是的,你是对的time.h

Here's my code:

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <share.h>
#include <time.h>


void f(long double fb[], long double fA, long double fB);

int main() {

clock_t start, end;
start = clock();


const int ARRAY_SIZE = 11;

long double* z = (long double*) malloc(sizeof (long double) * ARRAY_SIZE);

int i;
long double A, B;

if (z == NULL) {
    printf("Out of memory\n");
    exit(-1);
}

A = 0.5;
B = 2;


for (i = 0; i < ARRAY_SIZE; i++) {
    z[i] = 0;
}

z[1] = 5;

f(z, A, B);

for (i = 0; i < ARRAY_SIZE; i++)
    printf("z is %.16Le\n", z[i]);



free(z);
z = NULL;

end = clock();
printf("Took %ld ticks\n", end-start);
printf("Took %f seconds\n", (double)(end-start)/CLOCKS_PER_SEC);



return 0;  
}  

void f(long double fb[], long double fA, long double fB) {
    fb[0] = fb[1]* fA;
    fb[1] = fb[1] - 1;
    return;
 }  

Some errors with MVS2008:

MVS2008 的一些错误:

testim.c(16) : error C2143: syntax error : missing ';' before 'const'  
testim.c(18) :error C2143: syntax error : missing ';' before 'type'  
testim.c(20) :error C2143: syntax error : missing ';' before 'type'   
testim.c(21) :error C2143: syntax error : missing ';' before 'type'    
testim.c(23) :error C2065: 'z' : undeclared identifier   
testim.c(23) :warning C4047: '==' : 'int' differs in levels of indirection from 'void *'  
testim.c(28) : error C2065: 'A' : undeclared identifier
testim.c(28) : warning C4244: '=' : conversion from 'double' to 'int', possible loss of data   

and it goes to 28 errors. Note that I don't have any errors/warnings without your clock codes.

它会出现 28 个错误。请注意,没有您的时钟代码,我没有任何错误/警告。

LATEST NEWS:I unfortunately didn't get a good reply here. But after a search on Google, the code is working. Here it is:

最新消息:不幸的是,我在这里没有得到很好的答复。但是在谷歌上搜索后,代码正在运行。这里是:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>


void f(long double fb[], long double fA);

int main() {

clock_t start = clock();


const int ARRAY_SIZE = 11;

long double* z = (long double*) malloc(sizeof (long double) * ARRAY_SIZE);

int i;
long double A;

if (z == NULL) {
printf("Out of memory\n");
exit(-1);
}

A = 0.5;


for (i = 0; i < ARRAY_SIZE; i++) {
z[i] = 0;
}

z[1] = 5;

f(z, A);

for (i = 0; i < ARRAY_SIZE; i++)
printf("z is %.16Le\n", z[i]);



free(z);
z = NULL;

printf("Took %f seconds\n", ((double)clock()-start)/CLOCKS_PER_SEC);



return 0;
}

void f(long double fb[], long double fA) {
fb[0] = fb[1]* fA;
fb[1] = fb[1] - 1;
return;
}

Cheers

干杯

Update on April 10: Here's a better solution thanks to "JustJeff"

4 月 10 日更新:感谢“JustJeff”,这是一个更好的解决方案

#include <windows.h>
#include <stdio.h>
#include <stdlib.h>

void f(long double fb[], long double fA);

const int ARRAY_SIZE = 11;

int main(void)
{

   long double* z = (long double*) malloc(sizeof (long double) * ARRAY_SIZE);
   int i;
   long double A;

   LARGE_INTEGER freq;
   LARGE_INTEGER t0, tF, tDiff;
   double elapsedTime;
   double resolution;

   if (z == NULL) {
   printf("Out of memory\n");
   exit(-1);
   }
   QueryPerformanceFrequency(&freq);
   QueryPerformanceCounter(&t0);
   // code to be timed goes HERE
   {
    A = 0.5;


    for (i = 0; i < ARRAY_SIZE; i++) {
    z[i] = 0;
    }

    z[1] = 5;
    f(z, A);


    for (i = 0; i < ARRAY_SIZE; i++)
    printf("z is %.16Le\n", z[i]);

    free(z);
    z = NULL;

   }
QueryPerformanceCounter(&tF);
tDiff.QuadPart = tF.QuadPart - t0.QuadPart;
elapsedTime = tDiff.QuadPart / (double) freq.QuadPart;
resolution = 1.0 / (double) freq.QuadPart;
printf("Your performance counter ticks %I64u times per second\n", freq.QuadPart);
printf("Resolution is %lf nanoseconds\n", resolution*1e9);
printf("Code under test took %lf sec\n", elapsedTime);
return 0;
}


void f(long double fb[], long double fA) {
fb[0] = fb[1]* fA;
fb[1] = fb[1] - 1;
return;
}

It works both with MVS2008 and with Borland C++ builderX from 2003.

它适用于 MVS2008 和 2003 年的 Borland C++ builderX。

采纳答案by JustJeff

If you're on windows and you want to measure stuff down in the microseconds, investigate QueryPerformanceCounter() and QueryPerformanceFrequency(). On many systems these can resolve full processor clock periods, third of a nanosecond stuff, and I don't believe I've ever seen it any more coarse than 3.5795MHz, still well under a microsecond.

如果您在 Windows 上并且想要在微秒内测量内容,请研究 QueryPerformanceCounter() 和 QueryPerformanceFrequency()。在许多系统上,这些可以解析完整的处理器时钟周期,即 1/3纳秒,我相信我从未见过它比 3.5795MHz 更粗糙,仍远低于 1 微秒。

You call QueryPerformanceFrequency() to determine how many counts per second the counter counts. Then call QueryPerformanceCounter() before your code under test, and then again after. Delta the two readings of QPC and divide by the period from QPF and you get the elapsed time between the two QPC calls. Like so ...

您调用 QueryPerformanceFrequency() 来确定计数器每秒计数多少次。然后在测试代码之前调用 QueryPerformanceCounter(),然后再调用。将 QPC 的两个读数相乘并除以 QPF 的周期,您将得到两次 QPC 调用之间经过的时间。像这样...

LARGE_INTEGER freq;
LARGE_INTEGER t0, tF, tDiff;
double elapsedTime;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&t0);
// code to be timed goes HERE
QueryPerformanceCounter(&tF);
tDiff.QuadPart = tF.QuadPart - t0.QuadPart;
elapsedTime = tDiff.QuadPart / (double) freq.QuadPart;
// elapsedTime now has your measurement, w/resolution given by freq

Evidently these access a hardware counting device that is tied to some system oscillator on the main board, in which case they shouldn't suffer jitter from software load. The resolution you get depends on your system.

显然,这些访问硬件计数设备,该设备与主板上的某个系统振荡器相关联,在这种情况下,它们不应受到软件负载的抖动影响。您获得的分辨率取决于您的系统。

FOLLOW UP

跟进

Here's a very simple complete program that demonstrates the interface:

这是一个非常简单的完整程序,演示了界面:

#include <windows.h>
int main(void)
{
    LARGE_INTEGER freq;
    LARGE_INTEGER t0, tF, tDiff;
    double elapsedTime;
    double resolution;
    QueryPerformanceFrequency(&freq);
    QueryPerformanceCounter(&t0);
    // code to be timed goes HERE
    {
        Sleep(10);
    }
    QueryPerformanceCounter(&tF);
    tDiff.QuadPart = tF.QuadPart - t0.QuadPart;
    elapsedTime = tDiff.QuadPart / (double) freq.QuadPart;
    resolution = 1.0 / (double) freq.QuadPart;
    printf("Your performance counter ticks %I64u times per second\n", freq.QuadPart);
    printf("Resolution is %lf nanoseconds\n", resolution*1e9);
    printf("Code under test took %lf sec\n", elapsedTime);
    return 0;
}

For something as simple as this, it's quicker to skip the IDE, just save it in a foo.c file and (assuming MS VS 2008) use the command line

对于像这样简单的事情,跳过 IDE 会更快,只需将其保存在 foo.c 文件中并(假设是 MS VS 2008)使用命令行

cl foo.c

to build it. Here's the output on my system:

来建造它。这是我系统上的输出:

Your performance counter ticks 3579545 times per second
Resolution is 279.365115 nanoseconds
Code under test took 0.012519 sec

回答by Javier

On Unix (I think) systems, the timecommand with the name of your program as a command-line argument will tell you the time the program takes to run. Note that this measures the execution time of the whole program. If you need to test just one part, include time.hand use the clock function, more or less like this:

在 Unix(我认为)系统上,将time程序名称作为命令行参数的命令将告诉您程序运行所需的时间。请注意,这测量了整个程序的执行时间。如果你只需要测试一个部分,包括time.h和使用时钟功能,或多或少是这样的:

#include <time.h>

int main() {
    clock_t start;
    clock_t end;
    int function_time;
    start = clock();
    function_you_want_to_time();
    end = clock();
    /* Get time in milliseconds */
    function_time = (double)(end - start) / (CLOCKS_PER_SEC / 1000.0);
    return 0;
}

That will give you the time in milliseconds (notice the / 1000.0part). If you want seconds, remove / 1000.0. If you want plain clock ticks, which will be more accurate, make function_timea clock_tand replace the function_time = ...line with:

这将为您提供以毫秒为单位的时间(注意该/ 1000.0部分)。如果需要秒,请删除/ 1000.0. 如果您想要更准确的普通时钟滴答声,请制作function_time一个clock_t并将该function_time = ...行替换为:

function_time = end - start;

To time the whole program, I suggest to make a function called _main()or something, move all your program related code from main()(not the timing code!) to that function, and calling it from main(). That way, it's more clear what's the timing code and what's the rest of the program.

要对整个程序计时,我建议调用一个函数_main()或其他函数,将所有与程序相关的代码main()(不是计时代码!)移动到该函数,并从main(). 这样,就更清楚什么是计时代码,什么是程序的其余部分。

回答by Alex Budovski

You could use the clock()function (in <time.h>) if you want to test a block of code, or the timeprogram on *nix, as another answerer suggested. E.g.

如果您想测试代码块或*nix 上的程序,您可以使用该clock()函数 (in <time.h>) time,正如另一个回答者所建议的那样。例如

> time ./foo my args

For clock, you need to subtract the difference between two checkpoints. E.g.

对于时钟,您需要减去两个检查点之间的差异。例如

#include <time.h>

void f() {
  clock_t start, end;

  start = clock();

  // some long code.

  end = clock();
  printf("Took %ld ticks\n", end-start);
  // or in (fractional) seconds.
  printf("Took %f seconds\n", (double)(end-start)/CLOCKS_PER_SEC);
}

Update

更新

Regarding your new errors, you can't mix code and declarations in VC. You mustn't call any functions then continue to declare variables. Declare all your vars at the top, or compile with C++ mode.

关于你的新错误,你不能在 VC 中混合代码和声明。你不能调用任何函数然后继续声明变量。在顶部声明所有变量,或使用 C++ 模式编译。

回答by Draco Ater

If you need a total for your program then in Linux console:

如果您的程序需要总计,则在 Linux 控制台中:

$ time myProgram

You can also use time.h in your code.

您还可以在代码中使用 time.h。

#include <time.h>

int main(){
  time_t start, end;
  start = time(0);

  /* some working code */

  end = time(0);
  printf("%i seconds", end - start );
}

回答by Amber

You probably want time.h, and the clock()function.

您可能需要 time.h 和clock()函数。

回答by Jay

You can try GetTickCountalso. Clock will also work fine. But, I guess clock values will change if some other process or some one manually changes the system time, wheareas GetTickCount values are not affected by that.

您也可以尝试GetTickCount。时钟也能正常工作。但是,我猜如果某个其他进程或某个人手动更改系统时间,时钟值会发生变化,而 GetTickCount 值不受此影响。