时间(*time_t)没有得到当前时间(作业)

max*_*esa 1 c c++

我们正在做一些关于不同排序算法的报告.它们都在工作,但是在打印合并排序的处理时间时出现错误

我写了以下代码

...BubbleSort(arr3,50000);

time(&time_now); 
f = difftime(time_now,time_then);
printf("BubbleSort - tempo: %f\n",f);

time(&time_then); 
printf("then: %s",ctime(&time_then));
MergeSort(arr4,0,49999);

time(&time_now); 
printf("now: %s",ctime(&time_now)); 
f = difftime(time_now,time_then);

printf("MergeSort - tempo: %f\n",f);
Run Code Online (Sandbox Code Playgroud)

但它总是说时间= 0表示合并排序

在此输入图像描述

它似乎无法获得当前时间或mergesort的处理时间真的很低(但它确实有效),提前感谢

das*_*ght 7

您会看到零,因为您MergeSort的速度非常快,以至于它在您的系统上以可测量的时间间隔完成.

为您的程序提供更多数据以进行排序应该会有所帮助.或者,您可以更改时间测量机制以获得更精确的信息.但是,第二种方法依赖于系统.

执行时间MergeSort增长为N*log 2(N),因此要查看与BubbleSortN 2相比增长的时间,您需要为其提供更多的数据.对于50,000个项目的数组,数学计算大小约为3,000 .如果传递MergeSort大约50,000*3,000 = 150,000,000项的数组,则应该看到打印的非零数字.

注意:不要尝试将那么多数据传递给BubbleSort它 - 它需要很长时间才能完成,除非数据已经非常接近于排序.


Ser*_* L. 6

不要time用来计算程序/算法的运行时间.这是全局系统时间,包括抢占时间和运行后台的其他程序.

使用getrusage让您的代码的资源(CPU时间)的用法.

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



struct rusage start, end;
getrusage(RUSAGE_SELF, &start);

// run your code

getrusage(RUSAGE_SELF, &end);

struct timeval used_utime, used_stime;
timersub(&end.ru_utime, &start.ru_utime, &used_utime);
timersub(&end.ru_stime, &start.ru_stime, &used_stime);
printf("function ran for %d usec in user mode and %d usec in system mode \n"
    , used_utime.tv_sec * 1000 * 1000 + used_utime.tv_usec
    , used_stime.tv_sec * 1000 * 1000 + used_stime.tv_usec);
Run Code Online (Sandbox Code Playgroud)