【问题标题】:want to fetch CPU time, got想获取 CPU 时间,得到了
【发布时间】:2015-11-23 19:24:40
【问题描述】:
#ifdef WIN32
#else
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <conio.h>
#include <stdio.h>
#include <sys/timeb.h>
#include <time.h>
#include <conio.h>
#include <unistd.h>
#endif

int main()
{
 long time_ms;
#ifdef WIN32
struct _timeb timebuffer;
_ftime( &timebuffer );
time_ms = (long)timebuffer.time * 1000 + (long)timebuffer.millitm;
printf("Windows timing %ld", time_ms);

#else
struct timeval t1;
struct timezone tz;
gettimeofday(&t1, &tz);
time_ms = (t1.tv_sec) * 1000 + t1.tv_usec / 1000;
    printf("Other timing %ld", time_ms);
 #endif
//    return time_ms;
}`

错误:

这是完整代码的一部分,但是当我单独运行时遇到相同的错误,无法找到解决方案。 我附上了错误屏幕截图

【问题讨论】:

  • 删除#ifdef WIN32#else#endif
  • 您没有包含任何用于 Windows 编译的文件。所以它不识别结构和功能。
  • 屏幕截图显示您正在使用 Dev-C++。不。使用带有 MinGW 的 CodeBlocks 或 Visual Studio 的 Express/Community 版本(均免费)。

标签: c cpu-time


【解决方案1】:

gettimeofday 不会给你 CPU 花费在进程上的时间,它给你的是现实世界中的实时时间。你想要的是clock。这将告诉您程序已使用的处理时间。它是一个标准的 ISO C 函数,应该适用于任何 C 编译器。

请注意,它返回的值是以时钟滴答为单位的。要获得秒数,您必须将其除以 CLOCKS_PER_SEC。

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

int main(void) {
    clock_t cpu_time;

    for( int i = 1; i <= 10; i++ ) {
        cpu_time = clock();

        printf("CPU time used since program start is: %d clocks or %f seconds\n",
               (int)cpu_time,
               (float)cpu_time / CLOCKS_PER_SEC
        );
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多