Llinux Getting system time

Source: Internet
Author: User

Get the current time in Linux, the statistical program run time, you can use Gettimeofday () to get millisecond time statistics, using the RDTSC instruction to obtain nanosecond time statistics.

Gettimeofday ()

It is a Linux C library function that encapsulates the system call Sys_gettimeofday (), which in the x86_64 system calls Vsyscall () to access the kernel data, and the system calls Syscall on the X386 system.

Syscall and Vsyscall, only gettimeofday, time, getcpu these Linux C library functions of the system call Vsyscall, the rest are syscall.

The time cost analysis of this function:

Syscall system Call Implementation: The user state in the Syscall through the soft interrupt into the kernel, the CPU to do the work there, the user state switch to the kernel state, processing soft interrupt, save register value, copy the user state parameters to the kernel state, execution, the kernel state switch back to the user state, these processing process is more than 1ms.

Vsyscall system Call implementation: in the kernel state to create a shared memory, user-state can also access, and do not send interrupts, advantages: fast speed, low cost;

RDTSC directive

The RDTSC instruction is the X86 platform's read timestamp register TSC (64-bit) instruction, and the TSC register counts the elapsed time since the CPU started, and the TSC increments by 1 when each clock signal arrives.

The current CPU frequency >1ghz, so the clock cycle is the nanosecond level.

64-bit Register overflow time calculation: If the CPU frequency is 3ghz,1s within the TSC increased 3000000000,64bit register overflow required time: 2^64/3*10^9=6148914691.2s=194 years, it is generally not overflow.

The sample code for obtaining system Nanosecond time statistics using RDTSC is as follows (i386 system):

1 voidGetcurrtime (uint64_t&Now )2 {3 uint32_t lval, Hval;4Asmvolatile("RDTSC":"=a"(Lval),"=d"(Hval));5now =Hval;6now = (now << +) |lval;7}

Llinux Getting system time

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.