可以使用C标准库(Windows-Based & Unix-Based两方)的time函数取得精度为秒的时间,在Unix-Based系统中,使用gettimeofday函数取得更小精度的时间。
1 #include <stdio.h>
2 #include <stdlib.h>
3 #include <time.h>
4 #include <sys/time.h>
5 int main(int argc, char **argv)
6 {
7 const char A = 'a';
8 FILE *fp = NULL;
9 char * p = NULL;
10 long i = 0L;
11 long size = 0L;
12 time_t start = 0L;
13 time_t end = 0L;
14 struct timeval tv_start = {0};
15 struct timeval tv_end = {0};
16 p = *++argv;
17 if (p == NULL) {
18 printf("Input file size by mb, please. SIZE(mb) = ");
19 scanf("%d", &size);
20 }
21 if (size == 0L) {
22 size = atoi(p);
23 }
24 fp = fopen("dump.dat", "w");
25
26 if(fp == NULL)
27 {
28 perror("failed to open dump.dat");
29 return EXIT_FAILURE;
30 }
31 timerclear(&tv_start);
32 timerclear(&tv_end);
33 /// time(&start);
34 gettimeofday(&tv_start, NULL);
35 for (i = 0; i < 1024 * 1024 * size; i++)
36 {
37 fputc(A, fp);
38 }
39 gettimeofday(&tv_end, NULL);
40 /// time(&end);
41
42 start = tv_start.tv_sec * 1000000 + tv_start.tv_usec;
43 end = tv_end.tv_sec * 1000000 + tv_end.tv_usec;
44 printf("Wrote %d bytes. fclose(fp) %s.\n", i, fclose(fp) == 0 ? "succeeded" : "failed");
45 printf("TIME = %d.%3d s.\n", (end - start)/1000000, ((end - start)/1000)%1000);
46 return EXIT_SUCCESS;
47 }
48