In recent run some programs require computation time program running, and then search a bit related materials, following a good way to find, can achieve millisecond timing:
#include <sys/timeb.h>
#if defined(WIN32)
# define TIMEB _timeb
# define ftime _ftime
#else
#define TIMEB timeb
#endif
time_t ltime1, ltime2, tmp_time;
struct TIMEB tstruct1, tstruct2;
ftime (&tstruct1); // start time ms
time (<ime1); // start time s
//work
time (<ime2); // end time sec
ftime (&tstruct2); // end time ms
tmp_time = (ltime2 * 1000 + tstruct2.millitm) - (ltime1 * 1000 + tstruct1.millitm);
The following code may be a millisecond timing program in windows and linux internet.
Memory allocation procedure is thousands of times to time-consuming methods of presentation timing.
The main function ftime use of millisecond timing, use ftime can get the current time in seconds and milliseconds, so that we can get millisecond timing.
However, if you want to output time in milliseconds, you must use the 64 bit data type to represent. On linux is long long, while the windows using the __int64. Printf and if it is necessary to use the corresponding lower output 64-bit case. Otherwise, the output will be negative, then that overflow.
Under linux is: printf ( "% lld", n)
The windows are: printf ( "% I64d", n)
#include <stdio.h>
#include <sys/timeb.h>
#include <stdlib.h>
#if defined(WIN32)
# define TIMEB _timeb
# define ftime _ftime
typedef __int64 TIME_T;
#else
#define TIMEB timeb
typedef long long TIME_T;
#endif
int time_interval()
{
struct TIMEB ts1,ts2;
TIME_T t1,t2;
int ti;
ftime(&ts1);//开始计时
//do some work
{
int i;
for(i=0;i<100000;i++)
{
int *p=malloc(10000);
int *q=malloc(10000);
int *s=malloc(10000);
int *t=malloc(10000);
free(p);
free(q);
free(s);
free(t);
}
}
ftime(&ts2);//停止计时
t1=(TIME_T)ts1.time*1000+ts1.millitm;
printf("t1=%lld\n",t1);
t2=(TIME_T)ts2.time*1000+ts2.millitm;
printf("t2=%lld\n",t2);
ti=t2-t1;//获取时间间隔,ms为单位的
return ti;
}
int main()
{
int ti=time_interval();
printf("time interval=%d\n",ti);
}
But in fact, if you just get a simple interval, then they do not consider 64 questions, because the second one of the two time consuming subtracted, then the result is relatively small, the code is as follows:
#include <stdio.h>
#include <sys/timeb.h>
#include <stdlib.h>
#if defined(WIN32)
# define TIMEB _timeb
# define ftime _ftime
#else
#define TIMEB timeb
#endif
int time_interval()
{
struct TIMEB ts1,ts2;
time_t t_sec,ti;
ftime(&ts1);//开始计时
//do some work
{
int i;
for(i=0;i<100000;i++)
{
int *p=malloc(10000);
int *q=malloc(10000);
int *s=malloc(10000);
int *t=malloc(10000);
free(p);
free(q);
free(s);
free(t);
}
}
ftime(&ts2);//停止计时
t_sec=ts2.time-ts1.time;//计算秒间隔
t_ms=ts2.millitm-ts1.millitm;//计算毫秒间隔
ti=t_sec*1000+t_ms;
return ti;
}
int main()
{
int ti=time_interval();
printf("time interval=%d\n",ti);
}
Quoted from the following website:
https://www.cnblogs.com/xkfz007/archive/2011/11/14/2248394.html