Wechat search attention to “water drop and silver bullet” public account, the first time to obtain high-quality technical dry goods. 7 years of senior back-end research and development, to show you a different technical perspective.

Hi, I’m Kaito.

In this article, I want to talk with you about the topic of “time”.

Time passes by without notice, and we often call the “time API” when we write code. Have you ever thought about the rationale behind this?

There are many more questions about time, such as:

  • Why is computer time sometimes “wrong”?
  • How on earth does a computer “auto-calibrate” time?
  • What is UTC, the time we often see?
  • Does the “Beijing time” we see on the news really come from Beijing?

In this article, we reveal the secrets behind time.

This article is very interesting, I hope you can read it patiently.

Time why always go “not allowed”?

You’ve certainly met the situation where you buy a clock and, over time, discover that it doesn’t work properly.

Or, if a computer is not used for a long time, its time will also be skewed.

In these cases, you might disagree. If the time is not right, we will adjust it manually.

But have you ever stopped to wonder why their timing is getting worse and worse?

It’s not hard to answer that question. We just need to figure out how they got their time.

Clocks and computers have inside them something called a crystal oscillator, which vibrates at a fixed frequency when voltage is applied to it. But the “stability” of this vibration frequency depends on its manufacturing process and the influence of the external environment.

Because of the cost, the workmanship of the clock is not that high, so it is more prone to errors. And although computer manufacturing technology is relatively high, but its internal crystal oscillator will also be affected by “temperature” changes, in the working process, there will be errors.

They have a small margin of error, but over time the margin of error becomes more and more obvious.

Therefore, the computers we use today have the function of “automatic calibration” time. But how to calibrate it?

How to calibrate time?

It’s easy. Once you connect your computer to the Network, you’ll find that it automatically synchronizes with the Network time.

The question is, where did this “Internet time” come from?

I guess your brain’s first thought is that each computer must be equipped with a “time server,” which then synchronizes and calibrates automatically.

Yes, that’s true, not just for computers, but for phones, tablets, smartwatches and other devices that have an Internet connection.

Then continue to ask, this “time server” time is accurate?

In theory, it should also be a computer. Doesn’t it have the problems we mentioned earlier?

Besides, how exactly is this Internet time “synced” to our computers?

You might say, well, that must be through network packets.

The problem comes again, the network transmission data also has “delay”, synchronization server time, there is no error?

Linked together like a Russian doll, it’s hard to explain.

To get to the bottom of these questions, go back to the source of time.

Where does time come from?

Time is a very abstract concept. For many years, it has attracted numerous scientists, physicists and even philosophers to spend their whole lives to explain what the nature of time is. From the Big bang to space-time relativity, from black holes to quantum mechanics, time can be seen in this problem.

We do not discuss the inscrutable academic knowledge here, but focus on the very small scope of computers. But it’s not as simple as you might think.

Let’s start with the simplest one.

If you want to know how time is defined, you have to know how “day” comes from.

The answer is: look at the sun.

Because of the earth’s “rotation”, people can see the sunrise and sunset, people with sunrise and sunset, so this periodic phenomenon is defined as “day”.

In addition to its rotation, the Earth also revolves around the sun, so one revolution is defined as a “year”.

It can be seen from these phenomena that long ago, people used “astronomical phenomena” to determine time.

Later, in order to define time more accurately, people divided the day into 24 equal parts, which is called “time”.

Similarly, divide an hour into 60 “minutes” and a minute into 60 “seconds.”

Thus the basic unit of time, the second, was defined.

So, the relationship between the second and the day looks like this:

1 second = 1/24 * 60 * 60 = 1/86,400 days.

These definitions are related to the rotation of the earth and the sun.

However, it was later discovered that the earth’s orbit is not a perfect circle, but an “ellipse”, that is, the speed of the revolution is “uneven”, what does this mean?

Since the “day” is measured by observing the time it takes the sun to shine on the same spot on Earth, the orbit is elliptical, which means there is an error in the time it takes to shine on the same spot every day.

That is to say, the “day” calculated according to the earth’s revolution is not equal in length, and the second calculated according to the day is not equal in length.

Obviously, there is an error in the calculation here. What about this?

Smart people have figured out how to reduce the error by adding up all the days in a year, taking the average to get a relatively fixed number of days, and then calculating the relatively average number of seconds.

With astronomical laws established, people began to make “clocks” to show time.

From pendulum clocks to mechanical clocks, and then to the widely used quartz clocks in modern times, the production technology of clocks is getting higher and higher, and the time accuracy of modern quartz clocks is only “one thousandth of a second” per day.

So, in 1927, the first standard of Time was established, Universal Time (UT), based on “astronomical phenomena” and “timekeeping”.

Greenwich Mean Time (GMT) is Greenwich Mean Time because it is calculated at the Greenwich Observatory in London.

But as technology improved and our observations of the sun became more accurate, something interesting happened.

It is found that the rotation of the Earth is “not uniform” every day. The rotation of the Earth is affected by natural phenomena such as tides, crustal movements, melting glaciers, earthquakes and so on, and it is getting slower and slower!

What problems does this cause?

This would result in the average length of one day per year, which was previously prescribed, being different now.

For example, the average day in year 1 works out to be 23.9997 hours, year 2 might be 23.998 hours, year 3 might be 23.999 hours…

According to the definition of 1 second = 1/86400 days, the “second” of each year is also different.

This is more embarrassing, people with the earth from the basis of the definition of time, or not allowed!

You might be thinking, what’s wrong with making an error in time? Haven’t people lived for centuries on inaccurate astronomical phenomena?

Indeed, the impact on people’s basic lives is not that great. However, with the development of human activities, people begin to have more and more high precision time scenes.

For example, a difference of one hundredth of a second in a sporting event can determine the outcome, artillery shells need to be fired within a thousandth of a second accurately, radar technology even needs to be accurate to a millionth of a second…

Especially in the field of satellite launch, rocket test and so on, the high precision time system has also put forward higher and higher requirements!

How to do? How to solve the problem of inaccurate time completely?

Smart scientists began to wonder, if astronomical observations couldn’t solve the problem, could a better solution be found at the microscopic level?

At this point, they began to look at the “micro world”.

How long is a second?

Let’s go over our needs.

All along, our need to define “seconds” has essentially been to want a “perfectly stable” period, meaning that we expect every second to be of fixed “equal length.”

Time measurements based on astronomical observations and the earth’s rotation cannot do this.

At the microcosmic level, is there an element whose period of motion is “highly stable” and not affected by the environment?

Scientists began to explore along these lines…

Ok, now let’s go down to the atomic world.

Although an atom is small, it is a very complicated world inside.

Each atom has a nucleus lined with fast-moving electrons. When an atom is exposed to electromagnetic radiation, its orbital electrons can “jump” from one location to another. This is called a “transition” in physics.

It is found that when electrons in an atom transition, the atom will absorb or give off a certain amount of energy “electromagnetic wave”, this kind of electromagnetic wave is a kind of “periodic motion”, we can also regard it as the “oscillation” inside the atom.

Based on this principle, scientists began to experiment and study, trying to find a “short period, highly stable” movement of atoms.

Finally, scientists discovered that there is an atom, caesium, that oscillates shorter and more steadily than any other atom, and does so largely undisturbed by environmental factors.

After layer upon layer of experiments, scientists believe that it is the shortest and most stable element that can be measured on earth.

The scientists then measured the number of electron cycles within the cesium atom in a second, based on the previous definition of “second.” They came up with a total of 9,192,631,770 (9.1 billion + times).

Based on this, the scientists decided to “throw away” the astrometric second and redefine the duration of the “second” as this highly stable period of motion.

Therefore, in 1967, the International Congress of Weights and Measures decided to adopt, with the cesium atom transition 9192631770 cycles, the duration of the length of time defined as 1 second!

Note: the measurement principle and process are complicated, and the physical details are simplified here. You don’t have to worry too much about how this is measured, but you need to understand that the oscillation period inside this microscopic atom is very stable, and it’s much more accurate than the previous astronomical measurements of seconds.

Based on this oscillating cesium atom, we call it an atomic clock.

With atomic clocks, this means that every second the clock outputs is absolutely “isometric” and very stable. In this way, “accurate time keeping” is achieved!

How accurate can that be?

20 million years is exactly one second! You can see how accurate it is.

The scientific technology is still developing, and the precision equipment and measuring ability are getting higher and higher. The latest atomic clock can even reach exactly one second in 100 million years!

With Atomic clocks, a new Time standard called International Atomic Time, or TAI, was established.

Scientists stipulate that starting from 1958-01-01 00:00:00, atomic time, it every second, is a very precise second (fixed equal length), a solid second, completely stable second.

This is a great solution to the problem that seconds are not fixed.

So with this international atomic time, can it directly replace the previous said – astronomical phenomena timed “world time”?

The answer is no, the problem is far more complicated than imagined, why?

How did Universal Standard time come about?

Now, scientists have come up with two time scales:

  1. Universal time: Based on astronomical phenomena + clock timing, always matched with the earth’s rotation time
  2. International Atomic time: Based on atomic clocks, the period of each second is completely equal and fixed

What would happen if we took international atomic time as the time standard?

Because atomic time is very stable, but this is what happens when world time slows down as the Earth slows down:

  • Atomic time goes faster and universal time goes slower, and as time goes on, the gap between the two widens
  • Day after day, hundreds of years later, 12 o ‘clock in universal time is the moment when the sun shines high, while atomic time may be as late as 2 p.m
  • Thousands of years from now, when the sun shines high, atomic time may be as late as 8 p.m.

Can you imagine that at 8pm when the sun is shining?

It’s so subversive of our perception of life…

Universal time, based on astronomical measurements, has guided our human lives for thousands of years, and we are so used to this standard of time that it is surely unacceptable to be replaced by atomic time.

But what if there’s a conflict between atomic time, the highly stable standard of time keeping we need for scientific research?

The scientists started thinking again and finally came up with a compatible solution.

Since both sets of time standards are important, they should be retained and not replaced by each other.

We could create a “new standard of time” based on “atomic time” and start to keep time, with every second moving steadily and accurately.

In the meantime, to accommodate astrometry-based universal time, humans will “continuously observe” the difference between universal time and the new clock.

If the difference is too large, the clock is artificially adjusted (adding or subtracting a second) so that the difference is no more than 0.9 seconds.

For example, the clock itself goes faster than universal time, after a period of time, if the difference between the two is more and more big, then give this clock “add a second”, so that the clock in 23:59:59 next second into 23:59:60 seconds, so that it and universal time gap control within 0.9 seconds.

This operation is equivalent to making the fast clock “wait” for the slow universal time.

The extra second is what scientists call a leap second.

Isn’t that interesting? I’d heard of leap years, but didn’t expect leap seconds!

Of course, when the earth spins faster, it could be minus one second, jumping from 23:59:58 to 00:00:00. But that’s rare. For the most part, the Earth’s rotation is slowing down. A total of 27 leap seconds have been added worldwide, with the latest adjustment taking place on January 1, 2017 from 07:59:59 to 07:59:60 Beijing time.

The advantage of this is that the clock is still accurate to every second and takes into account the world of everyday use.

Scientists define the clock as Coordinated Universal Time (UTC) because it is based on the harmonization of atomic Time and Universal Time.

See? This is how UTC, which we often see in development, came about!

With this result, countries with the technical ability to build their own atomic clocks and then calculate COORDINATED Universal time.

And to further reduce the error of atomic clocks, each country will submit its utc calculations to an authority every month, which will then weigh them based on the accuracy of each country’s laboratories to produce the “final” UTC.

The final time is then sent to individual countries for “clock alignment” to keep the world within 100 nanoseconds.

At this point, scientists established a set of time standards, we use today “standard time”!

It is worth mentioning that China is also one of the countries cooperating with the calculation of COORDINATED Universal Time. This laboratory is the National Time Center of the Chinese Academy of Sciences, located in Lintong District, Xi ‘an city, Shaanxi Province, China, which continuously maintains China’s standard time.

Why was the National Time Center established in Shaanxi Province? Because Shaanxi province is geographically located in the middle of China, broadcasting time from this location is relatively even to each region of the country.

China then adds eight hours (China is in the 8th East Zone) to its own coordinated Universal Time (UTC), and the final time is “Beijing Time”!

Yes, that’s what we hear all the time on the news, Beijing time.

Isn’t that interesting? Beijing time was not created in Beijing, but in Shaanxi Province, with participation in the formulation and calibration of world time.

At this point, a new world standard time was established, which was officially established in 1972 and is still in use today.

With standard time, the question then is, how exactly is it synced to our computers, phones, and electronic devices?

This is “timing”.

How do computers synchronize time?

By now, we know how universal Standard Time and Beijing Time came from, but Beijing time was created in Shaanxi Province, is it necessary to calibrate a time here?

Obviously not.

The National Time Center of the Chinese Academy of Sciences in Shaanxi Province broadcasts Beijing Time in a series of ways, a process known as timing.

So how do we do that?

The National Time Center provides many ways to broadcast time, such as radio, Internet and telephone.

Radio waves usually travel faster and with less error, so the time center sends time this way to “time servers” around the country.

After the time server has the correct time, it broadcasts the time to the end users at the next layer through other means (such as the network).

After all this research, we can now explain the question at the beginning of the article.

A time server originally used to synchronize time through the national time center and then provide time synchronization service to other terminals.

So how do our computers keep up with it?

The simplest way, you might think, is for the client to “request” the server’s standard time, the server’s response time data, and the client to modify its “native time.”

But it’s not as simple as you think.

Because data takes time in the process of network transmission, the time will also affect the accuracy of the time.

How can I do that?

So they came up with a scheme that would take network delay into account when the computer was doing time calibration, and then “correct” the synchronized time to reduce the error.

Now, there’s software that does all of this, and if you know anything about operations, there’s a service called the Network Time Protocol (NTP) that starts on the server where we deploy our applications. It keeps the time of each machine in sync with the time server.

How does NTP synchronize server time?

There are two key points:

  1. How does NTP synchronize time?
  2. Does time synchronization affect running programs?

First, how does NTP synchronize time?

To put it simply, it corrects the local time by stamping “time stamps” on network packets and then calculating network latency.

You can calculate the network “transmission delay” and the “time difference” between the client and the server:

  • Network delay = (T4-T1) – (T3-T2)
  • Time difference = T2-T1-network delay / 2 = (t2-T1) + (T3-T4)) / 2

The calculation process assumes that the network path is symmetric and the delay is the same.

In this way, clients can “calibrate” their local time to keep it in sync with the server, a time error that ranges from 10ms to 500ms in wans to less than 1ms in lans.

Let’s look at the second question: when you synchronize time, does it affect the running program?

For example, we often write code like this:

T2 = time.now() // What if t2 is smaller than t1? elapsed = t2 - t1Copy the code

Is t2 really going to be less than T1?

There are two concepts involved: the wall clock and the monotonic clock. What’s the difference between them?

  • Wall clock: Usually referred to as coordinated Universal Time (UTC), the time may be set back after calibration
  • Monotonic clock: The number of nanoseconds the computer has experienced since it started, without calling back

The code we write, such as the “time API” called by the above program, usually takes the time from the wall clock, so if the time is calibrated, it can “go back in time”.

This must have a big impact on the program, how to solve this problem?

Fortunately, NTP provides two ways to calibrate the time:

  1. Ntpdate: Forcibly change the local time based on the server time
  2. NTPD: modify the time of the machine in the way of “smoothing things silently”, and spread the time difference to each small adjustment

In other words, when NTPD receives a time that needs to be “dialed back”, it makes the local time “slow” and gradually “aligns” with the server clock, so that the local time is still increasing, avoiding “rolling back”.

When configuring the NTP service, pay special attention to this situation. In addition, when writing programs, we should also pay attention to the time API is called to obtain the time, to avoid business logic exceptions.

So far, from the seemingly simple question of time, we dug step by step to the definition of time, and then how time is synchronized to the computer and terminal devices, how about that? Have you answered a lot of doubts in your mind?

conclusion

All right, so to sum up.

We’ve covered a lot of concepts in this article, so let’s go over them again.

1. In the early life of human beings, time was measured by observing “astronomical phenomena”. Based on the earth’s rotation law, a set of time standards was defined: “Universal time”.

2. Later, it was found that the earth’s orbit was elliptical, and the earth’s rotation was also affected by the earth’s interior, so its rotation speed became slower and slower. People found that the time calculated by universal time was “inaccurate”.

3. Scientists began to look for more stable periodic motion in the “microscopic world”, and finally determined the “atomic clock” based on the vibration frequency of the “cesium atom”, established the “world atomic time”, and redefined the length of the “second”, which is highly accurate.

4. However, as human social activities have become highly dependent on “universal time”, scientists based on the coordination of “atomic time” and “universal Time”, finally established a new time standard: “Coordinated Universal Time”, defined it as the global time standard, thus, the birth of universal standard time.

5. Based on coordinated Universal Time plus the difference of 8 hours in time zone, China established “Beijing Time” and broadcast it to the whole China.

6. The National Time Center broadcasts Beijing time to a national “time server” through which time used in our daily life, such as computers, is automatically synchronized and calibrated.

7. The computer completes the “automatic calibration” with the time server through NTP. Based on this, our application program can obtain the accurate time.

8. The NTP service should synchronize time in a quiet manner to avoid time “running backwards”.

Afterword.

This article is the most difficult one I have ever written, because it contains a lot of scientific knowledge, covering a much wider range than I had imagined.

When writing this article, I have read more than 30 materials at least. In many cases, I will be overwhelmed by a small detail and dig out more relevant knowledge in the field.

For example, how is the vibration frequency of a cesium atom measured? How can you measure it so accurately? Why do atomic clocks differ from country to country? How do computers deal with leap seconds? Where did time zones come from? What is the prime meridian? .

I didn’t go into a lot of detail, but I’ve tried to stay away from the hard physics and keep the important theoretical concepts, and HOPEFULLY you get the idea of how this works. If you don’t understand some details, you can try to read them several times first, and you can also communicate with me further.

At the same time, in the process of looking up data, I sincerely sigh at the greatness of human research results, and can reduce the time error to hundreds of millions of years of accuracy, and I can not express my admiration.

When we write code, it seems to call a simple time API, but have you ever thought about how many years of human wisdom behind it? I hope this article answers any questions you may have about time.

If you still want to learn the topic of time, also follow my public account “water drop and silver bullet”, reply “time” in the background, get more information I organized to learn.


Want to read more hardcore technology articles? Welcome to follow my public account”Water drops and silver bullets”.

I’m Kaito, a veteran backend programmer who thinks about technology. In my article, I will not only tell you what a technology point is, but also tell you why. I’ll also try to distill these thought processes into general methodologies that you can apply to other fields.