我想将输出从gethrtime转换为毫秒.
明显的做法是除以1000000.
不过,我经常这样做,想知道是否会成为瓶颈.
处理像1000000这样的数字时,是否有优化的分割操作?
注意:任何代码必须可移植.我使用gcc,这通常是在Sparc硬件上
#include <sys/time.h> #include <iostream> using namespace std; const double NANOSECONDS_TO_MILLISECONDS = 1.0 / 1000000.0; int main() { hrtime_t start; hrtime_t tmp; hrtime_t fin; start = gethrtime(); tmp = (hrtime_t)(start * NANOSECONDS_TO_MILLISECONDS); fin = gethrtime(); cout << "Method 1" cout << "Original val: " << start << endl; cout << "Computed: " << tmp << endl; cout << "Time:" << fin - start << endl; start = gethrtime(); tmp = (start / 1000000); fin = gethrtime(); cout "Method 2" cout << "Original val: " << start << endl; cout << "Computed: " << tmp << endl; cout << "Time:" << fin - start << endl; return 0; }
示例输出:
Original val: 3048161553965997 Computed: 3048161553 Time:82082 Original val: 3048161556359586 Computed: 3048161556 Time:31230 Original val: 3048239663018915 Computed: 3048239663 Time:79381 Original val: 3048239665393873 Computed: 3048239665 Time:31321 Original val: 3048249874282285 Computed: 3048249874 Time:81812 Original val: 3048249876664084 Computed: 3048249876 Time:34830
如果这是正确的,那么在这种情况下,乘以倒数实际上更慢.这可能是由于使用浮点数学而不是固定点数学.我只会坚持整数除法,根本不需要任何时间.
解决方法
部门不是一个昂贵的操作.如果您的应用程序的主要瓶颈是一个1000000分钟的操作,我非常怀疑.浮点处理器的速度比任何类型的“技巧”要快,而不仅仅是单次操作.