【问题标题】:always getting 0.00 when try to calculating execution time in C尝试在 C 中计算执行时间时总是得到 0.00
【发布时间】:2012-10-11 22:44:00
【问题描述】:

嘿,我正在尝试计算一个简单的多线程程序在 UBUNTU 上的执行时间。尽管我研究并使用了各种方法,但我总是得到 0.0000 的值。这是我的简单代码

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

clock_t startm, stopm;
#define START if ( (startm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define STOP if ( (stopm = clock()) == -1) {printf("Error calling clock");exit(1);}
#define PRINTTIME printf( "%6.9f seconds used by the processor.\n", ((double)stopm-startm)/CLOCKS_PER_SEC);

void* thread_function(int);
void function();

int total=0;
int counter;

pthread_mutex_t mutex1=PTHREAD_MUTEX_INITIALIZER;

int main(int argc, char* argv[]) {

    START
    counter = atoi(argv[1]);
    function();
    STOP
    PRINTTIME
    return;
}

void function(){
    int i;

    pthread_t t_array[counter];

    for(i=0; i<counter; i++){
        pthread_create(&t_array[i], NULL, thread_function, i);
    }

    for(i=0; i<counter; i++){
        pthread_join(t_array[i],NULL);
    }
    printf("Total = %d\n", total);
}

void* thread_function(int index){

   pthread_mutex_lock( &mutex1 );

   printf("Index : %d\n", index);
   total++;
   usleep(100000);

   pthread_mutex_unlock( &mutex1 );

}

如果您能提供帮助,我将不胜感激。

【问题讨论】:

  • 为什么不使用内置函数“时间”?只需使用time ./myProgram 调用您的程序即可。无需编写任何代码
  • 实际上这只是代码的缩短部分。我必须将该值作为两倍才能以正确的方式在屏幕上打印。有没有办法做到这一点_?
  • 我不明白:你必须用时间计算一些东西吗?调用time ./foo 在屏幕上打印经过的时间。 “以适当的方式”是什么意思?
  • clock() 测量 CPU 时间,usleep 不使用 CPU 时间,因此您的程序实际上几乎没有花费任何时间在 CPU 上。
  • @DanielFischer:事实上,时钟测量的是稀薄的空气。什么都没用。

标签: c time clock


【解决方案1】:

您似乎想在代码中为函数计时。考虑 gettimeofday()

#include <sys/types.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>

double now(void)
{
   struct timeval tv;
   double retval=0;
   gettimeofday(&tv, NULL);
   retval=tv.tv_usec;
   retval+= (double)tv.tv_usecs / 1000000.;
   return retval;
}

int main()
{
   double start=now();
   // run code here
   printf("elapsed time = %.6f"\n", now() - start);
   return 0;

}|

【讨论】:

  • POSIX.1-2008 将 gettimeofday() 标记为已过时,建议改用 clock_gettime(2)。
  • 是的,我希望在函数中使用时间计算,这很好用!谢谢你的回复:)
猜你喜欢
  • 1970-01-01
  • 2010-10-26
  • 1970-01-01
  • 1970-01-01
  • 2018-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多