1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| #include <sys/time.h> #include <time.h> #include <iostream> #include "tscns.h"
using namespace std;
uint64_t now() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000000 + tv.tv_usec; }
void* func_gettimeofday(void* p) { int32_t c = *(int32_t*)p; uint64_t start = now(); uint64_t us = 0; int i = 0; while (i++ < c) { struct timeval tv; gettimeofday(&tv, NULL); us += tv.tv_usec; }
cout << "gettimeofday(" << us << ") , times : " << c << endl; cout << "thread " << pthread_self() << " consume " << now() - start << " us" << endl; return 0; }
void* func_clockgettime(void* p) { int32_t c = *(int32_t*)p; uint64_t start = now(); uint64_t us = 0; int i = 0; while (i++ < c) { struct timespec tp; clock_gettime(CLOCK_REALTIME, &tp); us += tp.tv_nsec; }
cout << "clock_gettime(" << us << ") , times : " << c << endl; cout << "thread " << pthread_self() << " consume " << now() - start << " us" << endl;
return 0; }
void* func_tscns(void* p) { int32_t c = *(int32_t*)p; TSCNS tscns; tscns.init(); uint64_t start = now(); uint64_t temp = 0; int i = 0; while (i++ < c) { int64_t tsc = tscns.rdtsc(); temp += tsc; } cout << "tscns(" << temp << ") , times : " << c << endl; cout << "thread " << pthread_self() << " consume " << now() - start << " us" << endl;
return 0; }
int main(int argc, char** argv) { if (argc != 4) { cout << " [gettimeofday/clock_gettime] thread_number loop_count" << endl; exit(-1); } string mode = string(argv[1]); int n = atoi(argv[2]); int loop = atoi(argv[3]); pthread_t* ts = new pthread_t[n]; for (int i = 0; i < n; i++) { if (mode == "gettimeofday") { pthread_create(ts + i, NULL, func_gettimeofday, &loop);
} else if (mode == "clock_gettime") { pthread_create(ts + i, NULL, func_clockgettime, &loop);
} else if (mode == "tscns") { pthread_create(ts + i, NULL, func_tscns, &loop); } } for (int i = 0; i < n; i++) { pthread_join(ts[i], NULL); } delete[] ts; return 0; }
|