Linux下得到毫秒级时间
C程序:
1 #ifdef HAVE_CONFIG_H
2 #include <config.h>
3 #endif
4
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <sys/time.h>
8 int main(int argc, char *argv[])
9 {
10 printf("Hello, world!\n");
11 struct timeval tvafter,tvpre;
12 struct timezone tz;
13 int sum = 0;
14 int i=0;
15 gettimeofday (&tvpre , &tz);
16
17 for(i = 0; i < 100000000; i++)
18 {
19 sum += i;
20 }
21 gettimeofday (&tvafter , &tz);
22 printf("sum=%d 花费时间:%d\n",sum, (tvafter.tv_sec-tvpre.tv_sec)*1000+(tvafter.tv_usec-tvpre.tv_usec)/1000);
23 return EXIT_SUCCESS;
Perl程序
1 #!/usr/bin/perl -w
2
3 use strict;
4 use Time::HiRes qw(gettimeofday usleep);
5
6 my($start_sec, $start_usec, $end_sec, $end_usec, $time_used);
7
8 my $micro_sec = 1000000;
9
10 ($start_sec, $start_usec) = gettimeofday;
11
12 foreach(1..20)
13 {
14 print `date +\%H:\%M:\%S`;
15 usleep($micro_sec);
16 }
17
18 ($end_sec, $end_usec) = gettimeofday;
19 $time_used=($end_sec - $start_sec) + ($end_usec - $start_usec)/$micro_sec;
20
21 printf("time used:%.3fsec\n", $time_used);
22
23 exit 0;