demo实现:
///* 测量2个事件持续的时间 */
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// // #include<ctime>
// /*测试排序算法运行时间 c++*/
// void testSort(void(*sort)(int[], int), int arr[], int length)
// {
// clock_t startTime = clock();
// sort(arr, length);
// clock_t endTime = clock();
// // printf(double(endTime - startTime) / CLOCKS_PER_SEC,"s")
// }
// /*插入排序*/
// void insertionSort(int arr[], int n)
// {
// for (int i = 1; i < n; i++)
// {
// int e = arr[i];
// int j;
// for (j = i; j >0 && e < arr[j - 1]; j--)
// arr[j] = arr[j - 1];
// arr[j] = e;
// }
// }
//c语言实现
int main( void )
{
// /* 程序1: 调用函数计算程序时间 */
// int arrSize = 10000;
// int *arr = new int[arrSize];
// for (int i = 0; i < arrSize; i++)
// {
// arr[i] = rand() % arrSize;
// }
// testSort(insertionSort, arr, arrSize);//另一个程序
/* 程序2: 主函数内循环事件的程序运行时间 */
long i = 10000000L ; //表明这个数是long int类型。
clock_t start, end;
double duration;
/* 测量2个事件持续的时间 */
printf( " Time to do %ld empty loops is " , i );
start = clock(); //函数返回从“开启这个程序进程”到“程序中调用clock()函数”时之间的CPU时钟计时单元(clock tick)数
while ( i -- ) ; //第srand(time(NULL));
end = clock();
duration = ( double )(end - start) / CLOCKS_PER_SEC;
//CLOCKS_PER_SEC表示一秒钟内CPU运行的时钟周期数(时钟计时单元
printf( " %f seconds\n " , duration );
// system( " pause " );
return 0;
}
执行结果:
gcc readtxt.c -o readtxt && ./readtxt
Time to do 10000000 empty loops is 0.003350 seconds
time.h头文件:
#include <stdint.h>
#if defined(__APPLE__)
# include <mach/mach_time.h>
#elif defined(_WIN32)
# define WIN32_LEAN_AND_MEAN
# include <windows.h>
#else // __linux
# include <time.h>
# ifndef CLOCK_MONOTONIC //_RAW
# define CLOCK_MONOTONIC CLOCK_REALTIME
# endif
#endif
static
uint64_t nanotimer() {
static int ever = 0;
#if defined(__APPLE__)
static mach_timebase_info_data_t frequency;
if (!ever) {
if (mach_timebase_info(&frequency) != KERN_SUCCESS) {
return 0;
}
ever = 1;
}
return (mach_absolute_time() * frequency.numer / frequency.denom);
#elif defined(_WIN32)
static LARGE_INTEGER frequency;
if (!ever) {
QueryPerformanceFrequency(&frequency);
ever = 1;
}
LARGE_INTEGER t;
QueryPerformanceCounter(&t);
return (t.QuadPart * (uint64_t) 1e9) / frequency.QuadPart;
#else // __linux
struct timespec t;
if (!ever) {
if (clock_gettime(CLOCK_MONOTONIC, &t) != 0) {
return 0;
}
ever = 1;
}
clock_gettime(CLOCK_MONOTONIC, &t);
return (t.tv_sec * (uint64_t) 1e9) + t.tv_nsec;
#endif
}
static double now() {
static uint64_t epoch = 0;
if (!epoch) {
epoch = nanotimer();
}
return (nanotimer() - epoch) / 1e9;
};
double calcElapsed(double start, double end) {
double took = -start;
return took + end;
}
时间计算函数为:
double calcElapsed(double start, double end) {
double took = -start;
return took + end;
}
使用方法:
double startTime = now();//当前时间
nsProcess(inBuffer, sampleRate, inSampleCount, channels, kModerate);
double time_interval = calcElapsed(startTime, now());//结束计算时间的位置
参考:https://m.php.cn/manual/view/34332.html