尝试在 C 中计算执行时间时总是得到 0.00

  • 本文关键字:执行时间 计算 c time clock
  • 更新时间 :
  • 英文 :

嘿,我

正在尝试计算 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 = %dn", total);
}
void* thread_function(int index){
   pthread_mutex_lock( &mutex1 );
   printf("Index : %dn", index);
   total++;
   usleep(100000);
   pthread_mutex_unlock( &mutex1 );
}

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

看起来您想在代码中对函数进行计时。 考虑 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;
}|

最新更新