計算時間的副程式

精確度可以到 10 ms

// file: psc51.cpp
// for time1(), time2()

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <math.h>
#include <sys/timeb.h>
#include <time.h>
// ----------------------------------------------

#include "sj01.h"
// ----------------------------------------------

//   time1(&t1);
void time1(long *t1)
{
/* FTIME.C: This program uses _ftime to obtain the current
 * time and then stores this time in timebuffer.

millitm
Fraction of a second in milliseconds.

time
Time in seconds since midnight (00:00:00), January 1, 1970, coordinated universal time (UTC).
 */

   struct _timeb timebuffer;
   // char *timeline;
   long t2, t3, t4, t5, t6;

   _ftime( &timebuffer );
   // timeline = ctime( & ( timebuffer.time ) );

   t2= timebuffer.time;// 秒
   t3= t2%(1L*24L*60L*60L);
   t4= t3*1000L;

   t5= timebuffer.millitm;// 千分之ㄧ秒
   t6= t4 + t5;
   *t1= t6;

   // printf( "The time is %.19s.%hu %s", timeline, timebuffer.millitm, &timeline[20] );
   // printf("%ld, %ld, %ld, %ld, %ld, \n", 
   //	       t2,  t3,  t4,  t5,  t6);
}// end of time1()
// ----------------------------------------------

//   time2(     t1,        &dt);
void time2(long t1, double *dt)
{
	long t2;
	time1(&t2);

	*dt= (t2 - t1)/1000.0;

	// (*dt) >= 0
	if ((*dt) < 0) {
		(*dt)+= 1.0*24.0*60.0*60.0;
	}
}// end of time2()
// ----------------------------------------------

void main()
{
	int no, sum, i, ct1= 0;
	long t1;
	double dt;
	// ----------------------------------------------

	no= 10;
	skip(3);
	while (no > 0) {
		time1(&t1);

		sum= 0;
		for (i=1;i<=no;i++) {
			sum+= i;
		}
		time2(t1, &dt);
		// ----------------------------------------------

		ct1++;
		printf("ct1= %3ld, no= %12ld, sum= %12ld, t1= %8ld, dt= %8.4lf\n", 
			ct1, no, sum, t1, dt);

		if (dt > 0) {
			pause();
		}

		if (ct1>=16) {
			// break;
		}

		no*= 2;
	}

	skip(1);
	printf("*** end of program!\n");
}// end of main()

你可能感兴趣的:(c)