c - 测量 C 中函数所花费的时间总是 0.000000
问题描述
我阅读了geeksforgeeks的一篇文章。代码显示了一个测量时间函数成本的函数。
在我的机器上,无论我按多长时间,我总是得到 0.000000。
我打印 t = clock() - t; t 总是等于 0.00000,我将语句重写为这个,仍然得到 0.000000。
clock_t m;
m = clock() - t;
centos7中的gcc版本
[root@localhost log]# gcc --version
gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-28)
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
/* Program to demonstrate time taken by function fun() */
#include <stdio.h>
#include <time.h>
// A function that terminates when enter key is pressed
void fun()
{
printf("fun() starts \n");
printf("Press enter to stop fun \n");
while(1)
{
if (getchar())
break;
}
printf("fun() ends \n");
}
// The main program calls fun() and measures time taken by fun()
int main()
{
// Calculate the time taken by fun()
clock_t t;
t = clock();
fun();
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds
printf("fun() took %f seconds to execute \n", time_taken);
return 0;
}
解决方案
你好试试这个:
unsigned int t=time(0);
fun();
unsigned int result=time(0)-t; // result is the time taken by fun
推荐阅读
- ruby-on-rails - Rails 5 和 AWS Elastic Beanstalk 错误的数据库主机
- python - Bitmex Api 授权
- c# - 使用 Dapper 从数据库中检索用户 ID 失败
- c# - ef core new dbcontext 只执行一次 OnModelCreating
- java - 当我触摸用户开始聊天时出现问题
- php - 在同一个 HTML 表格中使用不同的数组变量来显示数据
- jquery - 从 Ajax 请求解析 Json 数据时出错
- c - 具有共享数据的 OpenMP 递归任务导致速度大幅下降
- angular9 - ngcc 中的错误已在 id xxxx 的进程中运行
- kubernetes - Apache Flink 作业未在 Kubernetes(副本)中的多个 TaskManager 上调度